Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

FC2a: a Material's storage buffers and its values frame by frame; parts with one spec share one Material (128/128)

shinyobjectz4f7944c4636e
diff --git a/Cargo.lock b/Cargo.lock
index 656fe17e..dbe373a3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14889,6 +14889,7 @@ dependencies = [
"raea-core-shape",
"raea-sys-frame",
"raea-sys-material",
+ "raea-sys-shader",
"raea-sys-three-shader",
"serde",
"serde_json",
diff --git a/bench/bevy-parity/examples.list b/bench/bevy-parity/examples.list
index ea8ebb5a..b060715a 100644
--- a/bench/bevy-parity/examples.list
+++ b/bench/bevy-parity/examples.list
@@ -127,3 +127,4 @@ shader/shader_defs
shader/shader_material_screenspace_texture
shader/shader_material_2d
shader/fallback_image
+shader/storage_buffer
diff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsv
index 666f418c..a5d0ca1c 100644
--- a/bench/bevy-parity/runs.tsv
+++ b/bench/bevy-parity/runs.tsv
@@ -126,3 +126,4 @@ shader/shader_defs - 10
shader/shader_material_screenspace_texture - 10,60
shader/shader_material_2d - 10
shader/fallback_image - 10
+shader/storage_buffer - 30,60
diff --git a/docs/bevy-parity.md b/docs/bevy-parity.md
index 749fbbfa..dd01602f 100644
--- a/docs/bevy-parity.md
+++ b/docs/bevy-parity.md
@@ -4,7 +4,7 @@ Bevy v0.20.0's examples against their raea TSX ports (docs/control.feature FC0a)
don't edit. An example passes when every probed frame passes pixels (SSIM 0.98 and no 32 px tile off by more than 24 of 255) and cost (batch keys and
frame time at most 1.25x the example's). Wall time is one machine's, measured in the same run.
-Examples: **438**, ported **127**, passing **127**, excluded **16** (docs/bevy-parity/excluded.tsv), left **295**.
+Examples: **438**, ported **128**, passing **128**, excluded **16** (docs/bevy-parity/excluded.tsv), left **294**.
raea's frame ms is its update's plus the time React takes to step a frame for its 3D (step), which the example
doesn't pay.
@@ -23,8 +23,6 @@ doesn't pay.
| stress_tests/many_foxes | 60 | 0.990304 | 3 | 2 / 2 | 30464 / 31511 | 7 / 9 | 3 / 3 | 5.442 / 5.279 = 5.279 + 0 | yes | |
| animation/animated_mesh | 30 | 0.996636 | 1 | 2 / 2 | 472 / 542 | 7 / 9 | 3 / 3 | 20.061 / 2.722 = 2.722 + 0 | yes | |
| animation/animated_mesh | 60 | 0.996594 | 1 | 2 / 2 | 472 / 542 | 7 / 9 | 3 / 3 | 4.062 / 2.175 = 2.175 + 0 | yes | |
-| shader/extended_material | 30 | 1.000000 | 0 | 0 / 0 | 448 / 511 | 6 / 8 | 1 / 2 | 18.283 / 1.669 = 1.669 + 0 | yes | |
-| shader/extended_material | 60 | 1.000000 | 0 | 0 / 0 | 448 / 511 | 6 / 8 | 1 / 2 | 3.139 / 1.26 = 1.26 + 0 | yes | |
| 3d/orthographic | 10 | 0.999503 | 0 | 5 / 2 | 446 / 515 | 10 / 9 | 6 / 3 | 46.082 / 2.443 = 2.443 + 0 | yes | |
| 3d/parenting | 30 | 0.999969 | 0 | 1 / 1 | 443 / 512 | 6 / 8 | 2 / 2 | 18.568 / 1.828 = 1.828 + 0 | yes | |
| 3d/parenting | 60 | 0.999968 | 0 | 1 / 1 | 443 / 512 | 6 / 8 | 2 / 2 | 3.63 / 1.367 = 1.367 + 0 | yes | |
@@ -163,7 +161,6 @@ doesn't pay.
| ui/text/multiline_text_input | 10 | 0.998036 | 6 | 0 / 0 | 487 / 508 | 5 / 7 | 1 / 1 | 43.521 / 2.048 = 2.048 + 0 | yes | |
| ui/text/multiple_text_inputs | 10 | 0.992332 | 12 | 0 / 0 | 517 / 508 | 5 / 7 | 1 / 1 | 44.057 / 1.326 = 1.326 + 0 | yes | |
| ui/text/text_input | 10 | 0.999094 | 12 | 0 / 0 | 448 / 508 | 5 / 7 | 1 / 1 | 45.526 / 1.135 = 1.135 + 0 | yes | |
-| ui/ui_material | 10 | 0.999993 | 0 | 0 / 0 | 446 / 510 | 5 / 7 | 1 / 1 | 43.096 / 1.166 = 1.166 + 0 | yes | |
| ui/text/system_fonts | 10 | 0.987943 | 18 | 0 / 0 | 1992 / 508 | 5 / 7 | 1 / 1 | 103.162 / 2.077 = 2.077 + 0 | yes | |
| ui/text/font_atlas_debug | 10 | 0.999660 | 6 | 0 / 0 | 445 / 508 | 5 / 7 | 1 / 1 | 44.418 / 2.053 = 2.053 + 0 | yes | |
| 3d/two_passes | 10 | 0.999025 | 0 | 2 / 2 | 444 / 513 | 7 / 9 | 3 / 3 | 49.497 / 3.914 = 3.914 + 0 | yes | |
@@ -183,14 +180,19 @@ doesn't pay.
| 2d/sprite_scale | 10 | 0.992281 | 11 | 0 / 0 | 486 / 532 | 5 / 7 | 1 / 1 | 45.502 / 2.239 = 2.239 + 0 | yes | |
| 2d/sprite_scale | 60 | 0.992281 | 11 | 0 / 0 | 486 / 532 | 5 / 7 | 1 / 1 | 2.28 / 1.553 = 1.553 + 0 | yes | |
| 2d/sprite_slice | 10 | 0.997293 | 11 | 0 / 0 | 464 / 521 | 5 / 7 | 1 / 1 | 43.511 / 1.426 = 1.426 + 0 | yes | |
-| shader/animate_shader | 30 | 1.000000 | 0 | 0 / 0 | 447 / 510 | 6 / 8 | 1 / 2 | 23.2 / 1.629 = 1.629 + 0 | yes | |
-| shader/animate_shader | 60 | 1.000000 | 0 | 0 / 0 | 447 / 510 | 6 / 8 | 1 / 2 | 3.338 / 1.465 = 1.465 + 0 | yes | |
-| shader/shader_defs | 10 | 0.999999 | 0 | 0 / 0 | 448 / 511 | 7 / 8 | 1 / 3 | 45.978 / 2.503 = 2.503 + 0 | yes | |
-| shader/shader_material_screenspace_texture | 10 | 0.998864 | 2 | 1 / 1 | 449 / 512 | 7 / 9 | 2 / 3 | 48.436 / 2.407 = 2.407 + 0 | yes | |
-| shader/shader_material_screenspace_texture | 60 | 0.998929 | 2 | 1 / 1 | 449 / 512 | 7 / 9 | 2 / 3 | 3.231 / 1.598 = 1.598 + 0 | yes | |
-| shader/shader_material_2d | 10 | 1.000000 | 0 | 0 / 0 | 447 / 510 | 6 / 8 | 1 / 1 | 45.128 / 1.489 = 1.489 + 0 | yes | |
-| shader/shader_material | 30 | 1.000000 | 0 | 0 / 0 | 447 / 510 | 6 / 8 | 1 / 2 | 19.131 / 1.539 = 1.539 + 0 | yes | |
-| shader/fallback_image | 10 | 1.000000 | 0 | 0 / 0 | 447 / 510 | 6 / 8 | 1 / 2 | 42.667 / 2.26 = 2.26 + 0 | yes | |
+| shader/storage_buffer | 30 | 0.999999 | 0 | 0 / 0 | 538 / 965 | 6 / 8 | 1 / 92 | 18.685 / 1.802 = 1.802 + 0 | yes | |
+| shader/storage_buffer | 60 | 0.999999 | 0 | 0 / 0 | 538 / 965 | 6 / 8 | 1 / 92 | 3.633 / 1.706 = 1.706 + 0 | yes | |
+| shader/extended_material | 30 | 1.000000 | 0 | 0 / 0 | 448 / 511 | 6 / 8 | 1 / 2 | 19.433 / 1.988 = 1.988 + 0 | yes | |
+| shader/extended_material | 60 | 1.000000 | 0 | 0 / 0 | 448 / 511 | 6 / 8 | 1 / 2 | 3.433 / 1.606 = 1.606 + 0 | yes | |
+| shader/animate_shader | 30 | 1.000000 | 0 | 0 / 0 | 447 / 511 | 6 / 8 | 1 / 2 | 23.168 / 2.181 = 2.181 + 0 | yes | |
+| shader/animate_shader | 60 | 1.000000 | 0 | 0 / 0 | 447 / 511 | 6 / 8 | 1 / 2 | 5.32 / 1.498 = 1.498 + 0 | yes | |
+| ui/ui_material | 10 | 0.999993 | 0 | 0 / 0 | 446 / 510 | 5 / 7 | 1 / 1 | 50.695 / 3.017 = 3.017 + 0 | yes | |
+| shader/shader_material | 30 | 1.000000 | 0 | 0 / 0 | 447 / 511 | 6 / 8 | 1 / 2 | 20.285 / 2.107 = 2.107 + 0 | yes | |
+| shader/shader_defs | 10 | 0.999999 | 0 | 0 / 0 | 448 / 512 | 7 / 8 | 1 / 3 | 49.424 / 1.777 = 1.777 + 0 | yes | |
+| shader/shader_material_screenspace_texture | 10 | 0.998864 | 2 | 1 / 1 | 449 / 513 | 7 / 9 | 2 / 3 | 48.937 / 3.225 = 3.225 + 0 | yes | |
+| shader/shader_material_screenspace_texture | 60 | 0.998929 | 2 | 1 / 1 | 449 / 513 | 7 / 9 | 2 / 3 | 3.417 / 1.736 = 1.736 + 0 | yes | |
+| shader/shader_material_2d | 10 | 1.000000 | 0 | 0 / 0 | 447 / 511 | 6 / 8 | 1 / 1 | 47.105 / 1.75 = 1.75 + 0 | yes | |
+| shader/fallback_image | 10 | 1.000000 | 0 | 0 / 0 | 447 / 511 | 6 / 8 | 1 / 2 | 46.188 / 2.415 = 2.415 + 0 | yes | |
## Excluded
diff --git a/docs/bevy-parity/results.jsonl b/docs/bevy-parity/results.jsonl
index 6b0237a2..928a7f72 100644
--- a/docs/bevy-parity/results.jsonl
+++ b/docs/bevy-parity/results.jsonl
@@ -10,8 +10,6 @@
{"example":"stress_tests/many_foxes","frame":60,"ssim":0.990304,"tile":3,"bevy":{"batch_keys":2,"entities":30464,"extents":["23.6615 34.9370 84.2011","23.6615 34.9370 84.2012","2500.0000 0.0000 2500.0000","78.2183 34.9370 91.5996","80.4108 34.9370 91.8799","84.3248 34.9370 92.3804","86.0376 34.9370 92.5995","86.0377 34.9371 92.5995"],"frame":60,"frame_ms":5.442,"materials":3,"mesh_entities":1001,"meshes":7,"other_material":0,"visible":1001},"raea":{"frame":70,"entities":31511,"mesh_entities":1001,"visible":1001,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["23.6613 34.9370 84.2011","23.6613 34.9371 84.2011","2500.0000 0.0000 2500.0000","78.2186 34.9370 91.5996","80.4110 34.9370 91.8800","84.3247 34.9370 92.3804","86.0374 34.9370 92.5994","86.0374 34.9371 92.5994"],"frame_ms":5.279,"step_ms":null,"cost_ms":5.279},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"animation/animated_mesh","frame":30,"ssim":0.996636,"tile":1,"bevy":{"batch_keys":2,"entities":472,"extents":["15.4187 42.8200 84.0474","250000.0000 0.0000 250000.0000"],"frame":30,"frame_ms":20.061,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":41,"entities":542,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["15.4187 42.8200 84.0474","250000.0000 0.0000 250000.0000"],"frame_ms":2.722,"step_ms":null,"cost_ms":2.722},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"animation/animated_mesh","frame":60,"ssim":0.996594,"tile":1,"bevy":{"batch_keys":2,"entities":472,"extents":["19.9546 34.9370 82.9540","250000.0000 0.0000 250000.0000"],"frame":60,"frame_ms":4.062,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":71,"entities":542,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["19.9546 34.9370 82.9540","250000.0000 0.0000 250000.0000"],"frame_ms":2.175,"step_ms":null,"cost_ms":2.175},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/extended_material","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["0.9945 1.0000 1.0000"],"frame":30,"frame_ms":18.283,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":37,"entities":511,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.9945 1.0000 1.0000"],"frame_ms":1.669,"step_ms":null,"cost_ms":1.669},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/extended_material","frame":60,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["0.9945 1.0000 1.0000"],"frame":60,"frame_ms":3.139,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":67,"entities":511,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.9945 1.0000 1.0000"],"frame_ms":1.26,"step_ms":null,"cost_ms":1.26},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"3d/orthographic","frame":10,"ssim":0.999503,"tile":0,"bevy":{"batch_keys":5,"entities":446,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame":10,"frame_ms":46.082,"materials":6,"mesh_entities":5,"meshes":10,"other_material":0,"visible":5},"raea":{"frame":17,"entities":515,"mesh_entities":5,"visible":5,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame_ms":2.443,"step_ms":null,"cost_ms":2.443},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"3d/parenting","frame":30,"ssim":0.999969,"tile":0,"bevy":{"batch_keys":1,"entities":443,"extents":["1.0000 1.0000 1.0000"],"frame":30,"frame_ms":18.568,"materials":2,"mesh_entities":2,"meshes":6,"other_material":0,"visible":2},"raea":{"frame":37,"entities":512,"mesh_entities":2,"visible":2,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["1.0000 1.0000 1.0000"],"frame_ms":1.828,"step_ms":null,"cost_ms":1.828},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"3d/parenting","frame":60,"ssim":0.999968,"tile":0,"bevy":{"batch_keys":1,"entities":443,"extents":["1.0000 1.0000 1.0000"],"frame":60,"frame_ms":3.63,"materials":2,"mesh_entities":2,"meshes":6,"other_material":0,"visible":2},"raea":{"frame":67,"entities":512,"mesh_entities":2,"visible":2,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["1.0000 1.0000 1.0000"],"frame_ms":1.367,"step_ms":null,"cost_ms":1.367},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
@@ -150,7 +148,6 @@
{"example":"ui/text/multiline_text_input","frame":10,"ssim":0.998036,"tile":6,"bevy":{"batch_keys":0,"entities":487,"extents":[],"frame":10,"frame_ms":43.521,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":508,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.048,"step_ms":null,"cost_ms":2.048},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/text/multiple_text_inputs","frame":10,"ssim":0.992332,"tile":12,"bevy":{"batch_keys":0,"entities":517,"extents":[],"frame":10,"frame_ms":44.057,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":508,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.326,"step_ms":null,"cost_ms":1.326},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/text/text_input","frame":10,"ssim":0.999094,"tile":12,"bevy":{"batch_keys":0,"entities":448,"extents":[],"frame":10,"frame_ms":45.526,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":508,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.135,"step_ms":null,"cost_ms":1.135},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"ui/ui_material","frame":10,"ssim":0.999993,"tile":0,"bevy":{"batch_keys":0,"entities":446,"extents":[],"frame":10,"frame_ms":43.096,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":510,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.166,"step_ms":null,"cost_ms":1.166},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/text/system_fonts","frame":10,"ssim":0.987943,"tile":18,"bevy":{"batch_keys":0,"entities":1992,"extents":[],"frame":10,"frame_ms":103.162,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":508,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.077,"step_ms":null,"cost_ms":2.077},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/text/font_atlas_debug","frame":10,"ssim":0.999660,"tile":6,"bevy":{"batch_keys":0,"entities":445,"extents":[],"frame":10,"frame_ms":44.418,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":508,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.053,"step_ms":null,"cost_ms":2.053},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"3d/two_passes","frame":10,"ssim":0.999025,"tile":0,"bevy":{"batch_keys":2,"entities":444,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame":10,"frame_ms":49.497,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":17,"entities":513,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame_ms":3.914,"step_ms":null,"cost_ms":3.914},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
@@ -170,11 +167,16 @@
{"example":"2d/sprite_scale","frame":10,"ssim":0.992281,"tile":11,"bevy":{"batch_keys":0,"entities":486,"extents":[],"frame":10,"frame_ms":45.502,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":532,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.239,"step_ms":null,"cost_ms":2.239},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"2d/sprite_scale","frame":60,"ssim":0.992281,"tile":11,"bevy":{"batch_keys":0,"entities":486,"extents":[],"frame":60,"frame_ms":2.28,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":67,"entities":532,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.553,"step_ms":null,"cost_ms":1.553},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"2d/sprite_slice","frame":10,"ssim":0.997293,"tile":11,"bevy":{"batch_keys":0,"entities":464,"extents":[],"frame":10,"frame_ms":43.511,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":521,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.426,"step_ms":null,"cost_ms":1.426},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/animate_shader","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":30,"frame_ms":23.2,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":37,"entities":510,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":1.629,"step_ms":null,"cost_ms":1.629},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/animate_shader","frame":60,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":60,"frame_ms":3.338,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":67,"entities":510,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":1.465,"step_ms":null,"cost_ms":1.465},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/shader_defs","frame":10,"ssim":0.999999,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["0.5000 0.5000 0.5000"],"frame":10,"frame_ms":45.978,"materials":1,"mesh_entities":2,"meshes":7,"other_material":2,"visible":2},"raea":{"frame":17,"entities":511,"mesh_entities":2,"visible":2,"meshes":8,"materials":3,"batch_keys":0,"other_material":2,"extents":["0.5000 0.5000 0.5000"],"frame_ms":2.503,"step_ms":null,"cost_ms":2.503},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/shader_material_screenspace_texture","frame":10,"ssim":0.998864,"tile":2,"bevy":{"batch_keys":1,"entities":449,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame":10,"frame_ms":48.436,"materials":2,"mesh_entities":2,"meshes":7,"other_material":1,"visible":2},"raea":{"frame":18,"entities":512,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":1,"other_material":1,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame_ms":2.407,"step_ms":null,"cost_ms":2.407},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/shader_material_screenspace_texture","frame":60,"ssim":0.998929,"tile":2,"bevy":{"batch_keys":1,"entities":449,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame":60,"frame_ms":3.231,"materials":2,"mesh_entities":2,"meshes":7,"other_material":1,"visible":2},"raea":{"frame":68,"entities":512,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":1,"other_material":1,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame_ms":1.598,"step_ms":null,"cost_ms":1.598},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/shader_material_2d","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":[],"frame":10,"frame_ms":45.128,"materials":1,"mesh_entities":0,"meshes":6,"other_material":0,"visible":0},"raea":{"frame":17,"entities":510,"mesh_entities":0,"visible":0,"meshes":8,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.489,"step_ms":null,"cost_ms":1.489},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/shader_material","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":30,"frame_ms":19.131,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":38,"entities":510,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":1.539,"step_ms":null,"cost_ms":1.539},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"shader/fallback_image","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":10,"frame_ms":42.667,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":17,"entities":510,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":2.26,"step_ms":null,"cost_ms":2.26},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/storage_buffer","frame":30,"ssim":0.999999,"tile":0,"bevy":{"batch_keys":0,"entities":538,"extents":["0.1500 0.1500 0.1500"],"frame":30,"frame_ms":18.685,"materials":1,"mesh_entities":91,"meshes":6,"other_material":91,"visible":91},"raea":{"frame":37,"entities":965,"mesh_entities":91,"visible":91,"meshes":8,"materials":92,"batch_keys":0,"other_material":91,"extents":["0.1500 0.1500 0.1500"],"frame_ms":1.802,"step_ms":null,"cost_ms":1.802},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/storage_buffer","frame":60,"ssim":0.999999,"tile":0,"bevy":{"batch_keys":0,"entities":538,"extents":["0.1500 0.1500 0.1500"],"frame":60,"frame_ms":3.633,"materials":1,"mesh_entities":91,"meshes":6,"other_material":91,"visible":91},"raea":{"frame":67,"entities":965,"mesh_entities":91,"visible":91,"meshes":8,"materials":92,"batch_keys":0,"other_material":91,"extents":["0.1500 0.1500 0.1500"],"frame_ms":1.706,"step_ms":null,"cost_ms":1.706},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/extended_material","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["0.9945 1.0000 1.0000"],"frame":30,"frame_ms":19.433,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":37,"entities":511,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.9945 1.0000 1.0000"],"frame_ms":1.988,"step_ms":null,"cost_ms":1.988},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/extended_material","frame":60,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["0.9945 1.0000 1.0000"],"frame":60,"frame_ms":3.433,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":67,"entities":511,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.9945 1.0000 1.0000"],"frame_ms":1.606,"step_ms":null,"cost_ms":1.606},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/animate_shader","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":30,"frame_ms":23.168,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":37,"entities":511,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":2.181,"step_ms":null,"cost_ms":2.181},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/animate_shader","frame":60,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":60,"frame_ms":5.32,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":67,"entities":511,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":1.498,"step_ms":null,"cost_ms":1.498},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"ui/ui_material","frame":10,"ssim":0.999993,"tile":0,"bevy":{"batch_keys":0,"entities":446,"extents":[],"frame":10,"frame_ms":50.695,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":510,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":3.017,"step_ms":null,"cost_ms":3.017},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/shader_material","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":30,"frame_ms":20.285,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":38,"entities":511,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":2.107,"step_ms":null,"cost_ms":2.107},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/shader_defs","frame":10,"ssim":0.999999,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["0.5000 0.5000 0.5000"],"frame":10,"frame_ms":49.424,"materials":1,"mesh_entities":2,"meshes":7,"other_material":2,"visible":2},"raea":{"frame":17,"entities":512,"mesh_entities":2,"visible":2,"meshes":8,"materials":3,"batch_keys":0,"other_material":2,"extents":["0.5000 0.5000 0.5000"],"frame_ms":1.777,"step_ms":null,"cost_ms":1.777},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/shader_material_screenspace_texture","frame":10,"ssim":0.998864,"tile":2,"bevy":{"batch_keys":1,"entities":449,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame":10,"frame_ms":48.937,"materials":2,"mesh_entities":2,"meshes":7,"other_material":1,"visible":2},"raea":{"frame":19,"entities":513,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":1,"other_material":1,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame_ms":3.225,"step_ms":null,"cost_ms":3.225},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/shader_material_screenspace_texture","frame":60,"ssim":0.998929,"tile":2,"bevy":{"batch_keys":1,"entities":449,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame":60,"frame_ms":3.417,"materials":2,"mesh_entities":2,"meshes":7,"other_material":1,"visible":2},"raea":{"frame":68,"entities":513,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":1,"other_material":1,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame_ms":1.736,"step_ms":null,"cost_ms":1.736},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/shader_material_2d","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":[],"frame":10,"frame_ms":47.105,"materials":1,"mesh_entities":0,"meshes":6,"other_material":0,"visible":0},"raea":{"frame":17,"entities":511,"mesh_entities":0,"visible":0,"meshes":8,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.75,"step_ms":null,"cost_ms":1.75},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader/fallback_image","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":10,"frame_ms":46.188,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":17,"entities":511,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":2.415,"step_ms":null,"cost_ms":2.415},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
diff --git a/runtime/look/src/parts.rs b/runtime/look/src/parts.rs
index 2ad018d3..d8c2bf62 100644
--- a/runtime/look/src/parts.rs
+++ b/runtime/look/src/parts.rs
@@ -41,3 +41,31 @@ pub fn keyed_vec(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its:
column(p, row, id, name, &its.iter().map(|i| at(i).unwrap_or(d[k])).collect::<Vec<_>>());
}
}
+
+/// A <Material>'s uniforms and storage buffers over the frames (docs/control.feature FC2a), sent as keyed
+/// `own:uniforms` component rows from each frame they change, which raea-sys-shader's own_live.rs packs into the
+/// part's Material; none when they never change (the spec the part is made with holds them). `spec` finds an item's
+/// Material spec: a mesh's material's `shader`, a 2D shape's own. Called after the part's row is pushed.
+pub fn own_uniforms(p: &mut Program, id: &str, its: &[Item], spec: impl Fn(&Item) -> Option<&Value>) {
+ let each: Vec<(usize, Value)> = its.iter().enumerate().filter_map(|(f, it)| {
+ let s = spec(it).filter(|s| s.get("own").is_some())?;
+ let v = serde_json::json!({ "uniforms": s.get("uniforms").cloned().unwrap_or(Value::Null), "buffers": s.get("buffers").cloned().unwrap_or(Value::Null) });
+ Some((f, serde_json::json!({ "type": "own:uniforms", "value": v })))
+ }).collect();
+ if each.windows(2).all(|w| w[0].1 == w[1].1) {
+ return;
+ }
+ // the part's spec carries its track's hash: parts share a Material (as Bevy's share one handle) only when their
+ // spec and every frame's values are the same (raea-sys-shader own.rs)
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ std::hash::Hash::hash(&each.iter().map(|(f, v)| format!("{f}{v}")).collect::<String>(), &mut h);
+ let track = format!("{:016x}", std::hash::Hasher::finish(&h));
+ let row = p.spawns.iter_mut().rev().flat_map(|(_, rows)| rows.iter_mut()).find(|r| r.get("id") == Some(&V::S(id.to_string())));
+ if let Some(V::S(s)) = row.and_then(|r| r.get_mut("shader")) {
+ if let Ok(Value::Object(mut o)) = serde_json::from_str::<Value>(s) {
+ o.insert("track".into(), Value::String(track));
+ *s = Value::Object(o).to_string();
+ }
+ }
+ keyed(p, "component", Some(id), "o", each.iter().map(|(f, v)| (*f, v)));
+}
diff --git a/runtime/plugins/Cargo.toml b/runtime/plugins/Cargo.toml
index c544ac53..c6345858 100644
--- a/runtime/plugins/Cargo.toml
+++ b/runtime/plugins/Cargo.toml
@@ -11,6 +11,7 @@ raea-sys-frame = { path = "../../systems/frame" }
raea-sys-material = { path = "../../systems/material" }
# three.js's shaders (docs/r3f.feature R3F11): a `three:uniforms` row patches a part's uniforms
raea-sys-three-shader = { path = "../../systems/three-shader" }
+raea-sys-shader = { path = "../../systems/shader" }
raea-core-program = { path = "../../core/program" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "bevy_state"] }
serde = "1"
diff --git a/runtime/plugins/src/reflect.rs b/runtime/plugins/src/reflect.rs
index 1ef40831..ea8690b5 100644
--- a/runtime/plugins/src/reflect.rs
+++ b/runtime/plugins/src/reflect.rs
@@ -70,6 +70,10 @@ pub fn insert_reflect(world: &mut World, e: Entity, path: &str, json: &Value) ->
if path == "three:uniforms" {
return raea_sys_three_shader::patch(world, e, json);
}
+ // a <Material>'s uniforms and storage buffers this frame (raea-sys-shader own_live.rs, docs/control.feature FC2a)
+ if path == "own:uniforms" {
+ return raea_sys_shader::own_live::patch(world, e, json);
+ }
let registry = world.resource::<AppTypeRegistry>().clone();
let reg = registry.read();
let r = registration(&reg, path)?;
diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rs
index d477358f..99f466e2 100644
--- a/runtime/scene/src/parts.rs
+++ b/runtime/scene/src/parts.rs
@@ -264,6 +264,7 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {
components(p, &id, &its);
material_fields(p, &id, &its);
three_uniforms(p, &id, &its);
+ own_uniforms(p, &id, &its, |it| it.material.as_ref()?.props.get("shader"));
}
}
diff --git a/runtime/scene2d/src/lib.rs b/runtime/scene2d/src/lib.rs
index e30e6181..dbff77c3 100644
--- a/runtime/scene2d/src/lib.rs
+++ b/runtime/scene2d/src/lib.rs
@@ -94,5 +94,6 @@ pub fn shapes(tracks: &[Track], p: &mut Program) {
place2d(p, &mut row, &id, &its, "#ffffff");
visible(p, &mut row, &id, track);
p.spawns.push(("shape2d".into(), vec![row]));
+ own_uniforms(p, &id, &its, |it| it.props.get("shader"));
}
}
diff --git a/runtime/scene3d/src/shaded.rs b/runtime/scene3d/src/shaded.rs
index 1c941ee1..f3cf04bf 100644
--- a/runtime/scene3d/src/shaded.rs
+++ b/runtime/scene3d/src/shaded.rs
@@ -25,6 +25,7 @@ type Made = HashMap<(AssetId<StandardMaterial>, u128), Handle<ShadedMaterial>>;
/// After apply_rows: each new mesh row's shader on, and the scene's built if these rows give one (a load clears the
/// last edit's first).
pub fn shade_rows(world: &mut World, inserted: &[Tup]) -> Result<(), String> {
+ world.remove_resource::<shader_ext::own::OwnMade>(); // a load's <Material>s share only among themselves
if let Some(t) = inserted.iter().find(|t| t.kind == "surface_shader") {
let v = spec(t)?;
let ext = shader_ext::build(world, &v, plugins::image).map_err(|e| format!("SurfaceShader: {e}"))?;
diff --git a/sdk/raea/bench/bevy-parity/shader/storage_buffer.tsx b/sdk/raea/bench/bevy-parity/shader/storage_buffer.tsx
new file mode 100644
index 00000000..9256ab98
--- /dev/null
+++ b/sdk/raea/bench/bevy-parity/shader/storage_buffer.tsx
@@ -0,0 +1,36 @@
+// Bevy v0.20.0 examples/shader/storage_buffer.rs in raea's TSX (docs/control.feature FC0a, FC2a): 13 x 7 cubes of
+// 0.3 m at (i, j, 0) for i in -6..=6 and j in -3..=3, each with a MeshTag (its index mod 5), all with the example's
+// own Material: assets/shaders/storage_buffer.wesl as written, its vertex and fragment shaders both, reading its
+// colours from a read-only storage buffer of five vec4s by the cube's tag. The example's update system writes the
+// buffer every update from the time (sin(t + i) / 2 + 0.5 and the same 2 and 4 later, t = 5 x elapsed seconds, in
+// f32), as the port's buffer does each frame. The camera at (0, 0, 10), in Bevy's default 1280 x 720 window.
+import { Composition, registerRoot, staticFile, useCurrentFrame } from "raea";
+import { Transform } from "raea/transform";
+import { Camera3d } from "raea/camera";
+import { Cuboid, Mesh3d } from "raea/mesh";
+import { BevyComponent } from "raea/3d";
+import { Material } from "@raea/render/bevy3d"; // raea/pbr once scene-loop lands (its pbr.ts commit)
+
+const SHADER = staticFile("shaders/storage_buffer.wesl");
+const f = Math.fround;
+const CUBES = Array.from({ length: 13 * 7 }, (_, n) => ({ x: Math.floor(n / 7) - 6, y: (n % 7) - 3, tag: n % 5 }));
+
+function Shot() {
+ // update: elapsed_secs as of this update (no delta on the first), t = elapsed x 5, each colour channel in f32
+ const t = f(f(useCurrentFrame() / 60) * 5);
+ const colors = Array.from({ length: 5 }, (_, i) => [0, 2, 4].map((k) => f(f(Math.sin(f(f(t + i) + k)) / 2) + 0.5)).concat(1));
+ return (
+ <>
+ {CUBES.map(({ x, y, tag }, n) => (
+ <Mesh3d key={n} transform={Transform.fromXyz(x, y, 0)}>
+ <Cuboid half_size={[0.15, 0.15, 0.15]} />
+ <Material fragment={SHADER} vertex={SHADER} buffers={{ colors }} />
+ <BevyComponent type="bevy_mesh::components::MeshTag" value={{ value: tag }} />
+ </Mesh3d>
+ ))}
+ <Camera3d transform={Transform.fromXyz(0, 0, 10).lookingAt([0, 0, 0])} />
+ </>
+ );
+}
+
+registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);
diff --git a/sdk/render/src/3d/materials.tsx b/sdk/render/src/3d/materials.tsx
index 5f9c6015..3ef08608 100644
--- a/sdk/render/src/3d/materials.tsx
+++ b/sdk/render/src/3d/materials.tsx
@@ -125,6 +125,8 @@ export interface SurfaceShaderSpec {
/** a <Material>'s own (docs/control.feature FC2a): its vertex shader file and what its Material methods give; set by
* <Material>, not on a ShaderExtension */
own?: OwnMaterialFields;
+ /** a <Material>'s read-only storage buffers, set by <Material> */
+ buffers?: Record<string, (number | number[])[]>;
}
/** What a <Material>'s Material methods give: vertex_shader, alpha_mode, depth_bias and the faces its specialize culls. */
@@ -186,7 +188,7 @@ export function assetPath(p: string): string {
/** A surface shader checked and given as the row's spec (its source, uniforms, textures). */
export function surfaceShader(owner: string, sh: SurfaceShaderSpec, hook: RegExp = HOOK, hooks = "fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>), fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32>, or its own @fragment"): Record<string, unknown> {
if (typeof sh !== "object" || sh === null) throw new TypeError(`${owner}: shader is { wesl | wgsl, uniforms, textures }`);
- const { wesl, wgsl, fragment, uniforms = {}, textures = {}, defs, own } = sh;
+ const { wesl, wgsl, fragment, uniforms = {}, textures = {}, defs, own, buffers } = sh;
if ([wesl, wgsl, fragment].filter((s) => s !== undefined).length !== 1) throw new TypeError(`${owner}: shader gives its source as wesl, wgsl or a fragment path, one of them`);
if (fragment !== undefined && (typeof fragment !== "string" || !fragment)) throw new TypeError(`${owner}: fragment is an asset path, got ${JSON.stringify(fragment)}`);
const src = wesl ?? wgsl;
@@ -207,7 +209,7 @@ export function surfaceShader(owner: string, sh: SurfaceShaderSpec, hook: RegExp
// code kept as given
const file = (s: unknown) => (typeof s === "string" && !s.includes(":") ? assetPath(s) : s);
const found = Object.fromEntries(Object.entries(textures).map(([k, t]) => [k, typeof t === "string" ? file(t) : t !== null && typeof t === "object" && "src" in t ? { ...t, src: file(t.src) } : t]));
- return { ...(fragment !== undefined ? { fragment: assetPath(fragment) } : wesl !== undefined ? { wesl } : { wgsl }), uniforms, textures: found, ...(defs !== undefined ? { defs: shaderDefs(owner, defs) } : {}), ...(own !== undefined ? { own, ...(own.vertex !== undefined ? { vertex: assetPath(own.vertex) } : {}) } : {}) };
+ return { ...(fragment !== undefined ? { fragment: assetPath(fragment) } : wesl !== undefined ? { wesl } : { wgsl }), uniforms, textures: found, ...(defs !== undefined ? { defs: shaderDefs(owner, defs) } : {}), ...(own !== undefined ? { own, ...(own.vertex !== undefined ? { vertex: assetPath(own.vertex) } : {}), ...(buffers !== undefined ? { buffers } : {}) } : {}) };
}
/** A shader's textures checked: up to 4 pictures and one array (docs/shaders.feature SH9). */
diff --git a/sdk/render/src/bevy3d/material.tsx b/sdk/render/src/bevy3d/material.tsx
index 153f13b8..727da0f3 100644
--- a/sdk/render/src/bevy3d/material.tsx
+++ b/sdk/render/src/bevy3d/material.tsx
@@ -5,10 +5,12 @@ import { surfaceShader, type SurfaceShaderSpec } from "../3d";
/** Your own Material (docs/control.feature FC2a): Bevy's `impl Material`, not an extension of StandardMaterial. Its
* fragment_shader() (and vertex_shader(), when `vertex` names one) is the file compiled as written: its imports (a
* `super::NAME` one reads NAME.wesl beside it), its own @fragment and its own `@group(MATERIAL_BIND_GROUP)` bindings,
- * up to 8 uniforms of any type (a struct's from { field: value }), 4 textures and their samplers, in its layout. A
- * uniform or texture it doesn't declare is refused. `alpha_mode` and `depth_bias` are its Material methods', and
- * `cull_mode` the faces its specialize culls (the pipeline's by default: Back in 3D, none in 2D; null culls none). In
- * a Mesh2d it is Bevy's Material2d (its group 2), in place of the ColorMaterial.
+ * up to 8 uniforms of any type (a struct's from { field: value }), 2 read-only storage buffers, a texture_2d and
+ * sampler 4 times and one texture of each other dimension, in its layout; one it declares and isn't given binds
+ * Bevy's fallback image. A uniform, buffer or texture it doesn't declare is refused. Its uniforms and buffers may
+ * change from frame to frame, as an example's update system changes them. `alpha_mode` and `depth_bias` are its
+ * Material methods', and `cull_mode` the faces its specialize culls (the pipeline's by default: Back in 3D, none in
+ * 2D; null culls none). In a Mesh2d it is Bevy's Material2d (its group 2), in place of the ColorMaterial.
* @bevy bevy_pbr::material::Material */
export interface MaterialProps {
/** the shader file, staticFile("shaders/x.wesl"), as Bevy's Material::fragment_shader names one */
@@ -16,6 +18,9 @@ export interface MaterialProps {
/** a vertex shader file, as Material::vertex_shader names one (Bevy's mesh vertex shader when not given) */
vertex?: string;
uniforms?: Record<string, number | number[] | string | Record<string, number | number[] | string>>;
+ /** its read-only storage buffers (`var<storage, read> NAME: array<T(, N)>`, up to 2): each a list of its elements, a
+ * number or [x, y(, z(, w))] each, as Bevy's ShaderBuffer::from(Vec<[f32; 4]>) holds them */
+ buffers?: Record<string, (number | number[])[]>;
textures?: SurfaceShaderSpec["textures"];
defs?: SurfaceShaderSpec["defs"];
alpha_mode?: AlphaMode;
@@ -27,7 +32,8 @@ const ALPHA = ["Opaque", "Blend", "Premultiplied", "Add", "Multiply", "AlphaToCo
/** A Material's props checked, as the shader spec it is drawn by (in a Mesh3d an OwnMaterial, in a Mesh2d its
* Material2d). */
-function ownSpec({ fragment, vertex, uniforms, textures, defs, alpha_mode, depth_bias, cull_mode }: MaterialProps): SurfaceShaderSpec {
+function ownSpec({ fragment, vertex, uniforms, buffers, textures, defs, alpha_mode, depth_bias, cull_mode }: MaterialProps): SurfaceShaderSpec {
+ for (const [k, b] of Object.entries(buffers ?? {})) if (!Array.isArray(b) || !b.every((x) => Number.isFinite(x) || (Array.isArray(x) && x.length >= 2 && x.length <= 4 && x.every(Number.isFinite)))) throw new TypeError(`Material: buffer ${k} is a list of numbers or [x, y(, z(, w))], got ${JSON.stringify(b)}`);
if (typeof fragment !== "string" || !fragment) throw new TypeError(`Material: fragment is the shader file, staticFile("shaders/x.wesl"), got ${JSON.stringify(fragment)}`);
if (vertex !== undefined && (typeof vertex !== "string" || !vertex)) throw new TypeError(`Material: vertex is a shader file, got ${JSON.stringify(vertex)}`);
const mask = typeof alpha_mode === "object" && alpha_mode !== null && Number.isFinite((alpha_mode as { Mask?: number }).Mask);
@@ -35,7 +41,7 @@ function ownSpec({ fragment, vertex, uniforms, textures, defs, alpha_mode, depth
if (depth_bias !== undefined && !Number.isFinite(depth_bias)) throw new TypeError(`Material: depth_bias is a number, got ${depth_bias}`);
if (cull_mode !== undefined && cull_mode !== null && cull_mode !== "Front" && cull_mode !== "Back") throw new TypeError(`Material: cull_mode is "Front", "Back" or null, got ${JSON.stringify(cull_mode)}`);
const own = { ...(vertex !== undefined ? { vertex } : {}), ...(alpha_mode !== undefined ? { alpha_mode } : {}), ...(depth_bias !== undefined ? { depth_bias } : {}), ...(cull_mode !== undefined ? { cull_mode } : {}) };
- return { fragment, uniforms: uniforms as SurfaceShaderSpec["uniforms"], textures, defs, own };
+ return { fragment, uniforms: uniforms as SurfaceShaderSpec["uniforms"], textures, defs, own, ...(buffers ? { buffers } : {}) };
}
export function Material(p: MaterialProps) {
diff --git a/systems/shader/src/layout.rs b/systems/shader/src/layout.rs
index 691ed83f..bce1e0f0 100644
--- a/systems/shader/src/layout.rs
+++ b/systems/shader/src/layout.rs
@@ -65,7 +65,7 @@ fn find_struct(src: &str, name: &str) -> Option<usize> {
}
/// A field's WGSL type as (scalar kind, components): f32, u32 or i32, alone or in a vec2/3/4
-fn kind(t: &str) -> Option<(char, usize)> {
+pub(crate) fn kind(t: &str) -> Option<(char, usize)> {
let t = t.replace(' ', "");
let scalar = |s: &str| match s {
"f32" => Some('f'),
@@ -87,6 +87,15 @@ fn kind(t: &str) -> Option<(char, usize)> {
None
}
+/// One component's 32 bits as its kind ('f', 'u' or 'i', kind's) holds it: a u32 or i32 rounded, a u32 at least 0.
+pub(crate) fn word(k: char, x: f32) -> u32 {
+ match k {
+ 'f' => x.to_bits(),
+ 'u' => x.round().max(0.0) as u32,
+ _ => (x.round() as i32) as u32,
+ }
+}
+
/// The uniforms laid out in `fields` (WGSL's uniform layout: a scalar aligned to 4, a vec2 to 8, a vec3 or vec4 to 16)
/// in 256 bytes. Each field takes the uniform of its name; every field needs one, and every uniform a field.
pub fn pack(fields: &[(String, String)], uniforms: &[(String, Vec4)]) -> Result<[Vec4; 16], String> {
@@ -105,12 +114,7 @@ pub fn pack(fields: &[(String, String)], uniforms: &[(String, Vec4)]) -> Result<
}
let v = uniforms.iter().find(|(u, _)| u == name).map(|(_, v)| *v).ok_or_else(|| format!("the shader's uniform struct has {name}, which the uniforms don't give"))?;
for c in 0..n {
- let x = v[c];
- words[at + c] = match k {
- 'f' => x.to_bits(),
- 'u' => x.round().max(0.0) as u32,
- _ => (x.round() as i32) as u32,
- };
+ words[at + c] = word(k, v[c]);
}
at += n;
}
diff --git a/systems/shader/src/lib.rs b/systems/shader/src/lib.rs
index 6e249b0b..444dad1e 100644
--- a/systems/shader/src/lib.rs
+++ b/systems/shader/src/lib.rs
@@ -28,6 +28,7 @@ use raea_sys_material::shader_material::{defs, ident, uniform, Uniform, SLOTS, T
mod layout;
pub mod own;
+pub mod own_live;
pub mod ui;
mod ui_bind;
@@ -304,9 +305,8 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Va
pub fn put(world: &mut World, e: Entity, v: &Value, mut image: impl FnMut(&mut World, &Value) -> Result<Handle<Image>, String>, made: &mut HashMap<(AssetId<StandardMaterial>, u128), Handle<ShadedMaterial>>) -> Result<(), String> {
// a <Material>'s spec has its `own` (own.rs)
if v.get("own").is_some() {
- let m = own::build(world, v, &mut image, false)?;
- own::put(world, e, m);
- return Ok(());
+ let m = own::shared(world, v, &mut image, false)?;
+ return own::put(world, e, m);
}
let ext = build(world, v, image)?;
shade(world, e, &ext, made);
diff --git a/systems/shader/src/own.rs b/systems/shader/src/own.rs
index 34e747bd..09584514 100644
--- a/systems/shader/src/own.rs
+++ b/systems/shader/src/own.rs
@@ -11,17 +11,20 @@
//! which is the module path WESL resolves `super::NAME` to.
use std::hash::{Hash, Hasher};
+use std::sync::Arc;
use bevy::asset::uuid_handle;
use bevy::mesh::MeshVertexBufferLayoutRef;
use bevy::pbr::{Material, MaterialPipeline, MaterialPipelineKey, MaterialPlugin};
use bevy::prelude::*;
use bevy::render::render_resource::{AsBindGroup, Face, RenderPipelineDescriptor, SpecializedMeshPipelineError};
+use bevy::render::storage::ShaderBuffer;
use bevy::shader::{Shader, ShaderRef};
use bevy::sprite_render::{AlphaMode2d, Material2d, Material2dKey, Material2dPipeline, Material2dPlugin};
use serde_json::Value;
-use crate::ui_bind::{rebind_in, Rebound, DIMS};
+use crate::own_live::{storage, Packing};
+use crate::ui_bind::{rebind_in, Rebound};
use crate::{layout, register, Inputs, OwnSurface, Shaded};
/// The fragment shader every pipeline starts from, swapped in `specialize` for the material's own (its uuid).
@@ -81,6 +84,13 @@ pub struct OwnMaterial {
cube_array: Option<Handle<Image>>,
#[texture(22, dimension = "3d")]
d3: Option<Handle<Image>>,
+ // its read-only storage buffers (ui_bind.rs STORAGE); one it doesn't bind holds 16 zero bytes
+ #[storage(23, read_only)]
+ b0: Handle<ShaderBuffer>,
+ #[storage(24, read_only)]
+ b1: Handle<ShaderBuffer>,
+ /// what its uniforms and buffers are packed from, for a frame's new values (own_live.rs)
+ pub(crate) packing: Arc<Packing>,
shader: u128,
/// the vertex shader's uuid, 0 for Bevy's mesh vertex shader
vertex: u128,
@@ -90,6 +100,17 @@ pub struct OwnMaterial {
cull: Option<Option<Face>>,
}
+impl OwnMaterial {
+ /// Its storage buffers, in slot order.
+ pub(crate) fn buffers(&self) -> [Handle<ShaderBuffer>; 2] {
+ [self.b0.clone(), self.b1.clone()]
+ }
+ /// Its uniforms' slots, packed again (own_live.rs patch).
+ pub(crate) fn set_slots(&mut self, s: [[Vec4; 16]; 8]) {
+ [self.u0, self.u1, self.u2, self.u3, self.u4, self.u5, self.u6, self.u7] = s;
+ }
+}
+
/// What picks a pipeline: the material's shaders and the faces it culls.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct OwnKey {
@@ -176,8 +197,9 @@ pub fn build(world: &mut World, v: &Value, image: &mut impl FnMut(&mut World, &V
// the uniforms are packed in the source's own types below, so Inputs reads the rest
let mut rest = o.clone();
let given = rest.remove("uniforms").and_then(|u| u.as_object().cloned()).unwrap_or_default();
+ let buffers = rest.remove("buffers").and_then(|u| u.as_object().cloned()).unwrap_or_default();
let ins = Inputs::read(world, &rest, what, image)?;
- let Rebound { src, uniforms, textures, others, .. } = rebind_in(&ins.src, groups, what, true).map_err(|e| format!("{path}: {e}"))?;
+ let Rebound { src, uniforms, textures, others, storages, .. } = rebind_in(&ins.src, groups, what, true).map_err(|e| format!("{path}: {e}"))?;
let [u0, u1, u2, u3, u4, u5, u6, u7] = layout::slots(&src, &uniforms, &given, &ins.defs).map_err(|e| format!("{path}: {e}"))?;
if let Some((k, _)) = ins.textures.iter().find(|(k, _)| !textures.contains(k)) {
return Err(format!("{path} has no texture_2d {k}"));
@@ -191,9 +213,24 @@ pub fn build(world: &mut World, v: &Value, image: &mut impl FnMut(&mut World, &V
// the other dimensions: a 2d_array from the spec's one texture array ({layers}); the rest are fallbacks for now
let mut dims: [Option<Handle<Image>>; 5] = Default::default();
if let Some((name, h)) = &ins.array {
- let i = others.iter().position(|(n, d)| n == name && *d == "2d_array").ok_or_else(|| format!("{path} has no texture_2d_array {name}"))?;
- dims[DIMS.iter().position(|x| x.1 == others[i].1).unwrap_or(1)] = Some(h.clone());
+ if !others.iter().any(|(n, d)| n == name && *d == "2d_array") {
+ return Err(format!("{path} has no texture_2d_array {name}"));
+ }
+ dims[1] = Some(h.clone());
+ }
+ // its storage buffers from the spec's `buffers`, each in its declared type's layout
+ if let Some(k) = buffers.keys().find(|k| !storages.iter().any(|(n, _)| n == *k)) {
+ return Err(format!("{path} has no storage buffer {k}"));
+ }
+ let mut b = Vec::new();
+ for (name, ty) in &storages {
+ let v = buffers.get(name).ok_or_else(|| format!("{path}'s storage buffer {name} has no value"))?;
+ b.push(world.resource_mut::<Assets<ShaderBuffer>>().add(storage(name, ty, v).map_err(|e| format!("{path}: {e}"))?));
+ }
+ while b.len() < 2 {
+ b.push(world.resource_mut::<Assets<ShaderBuffer>>().add(ShaderBuffer::from(vec![0u32; 4])));
}
+ let packing = Arc::new(Packing { src: src.clone(), uniforms, storages, defs: ins.defs.clone() });
let krate = folder(world, path, &src)?;
let shader = register(world, src, &ins.defs, "raea own material", &krate);
let vertex = match o.get("vertex").and_then(Value::as_str) {
@@ -217,7 +254,7 @@ pub fn build(world: &mut World, v: &Value, image: &mut impl FnMut(&mut World, &V
};
let [t0, t1, t2, t3] = t;
let [d1, d2a, cube, cube_array, d3] = dims;
- Ok(OwnMaterial { u0, u1, u2, u3, u4, u5, u6, u7, t0, t1, t2, t3, d1, d2a, cube, cube_array, d3, shader, vertex, alpha, depth_bias, cull })
+ Ok(OwnMaterial { u0, u1, u2, u3, u4, u5, u6, u7, t0, t1, t2, t3, d1, d2a, cube, cube_array, d3, b0: b[0].clone(), b1: b[1].clone(), packing, shader, vertex, alpha, depth_bias, cull })
}
/// Bevy's AlphaMode as the SDK writes it: "Opaque", "Blend", {"Mask": cutoff}, "Premultiplied", "AlphaToCoverage",
@@ -300,13 +337,33 @@ fn siblings(src: &str) -> Vec<String> {
out
}
+/// The Materials made this load, by their spec (its track of values included, raea-runtime-look own_uniforms): parts
+/// with one spec share one, as Bevy's examples share a handle (shader/storage_buffer's 91 cubes draw with one).
+#[derive(Resource, Default)]
+pub struct OwnMade(pub std::collections::HashMap<String, Handle<OwnMaterial>>);
+
+/// The Material for a spec: the one made already for the same spec (in 3D or 2D), or a new one (`build`).
+pub fn shared(world: &mut World, v: &Value, image: &mut impl FnMut(&mut World, &Value) -> Result<Handle<Image>, String>, two_d: bool) -> Result<Handle<OwnMaterial>, String> {
+ let key = format!("{two_d} {v}");
+ if let Some(h) = world.get_resource::<OwnMade>().and_then(|m| m.0.get(&key)).cloned() {
+ return Ok(h);
+ }
+ let m = build(world, v, image, two_d)?;
+ let h = world.resource_mut::<Assets<OwnMaterial>>().add(m);
+ world.get_resource_or_init::<OwnMade>().0.insert(key, h.clone());
+ Ok(h)
+}
+
/// A part given its own Material: its MeshMaterial3d<StandardMaterial> swapped for the OwnMaterial, the standard one
/// kept aside as `Shaded` (so the rows' sync finds it) and the scene's <SurfaceShader> kept off it.
-pub fn put(world: &mut World, e: Entity, m: OwnMaterial) -> bool {
- let Some(std) = world.get::<MeshMaterial3d<StandardMaterial>>(e).map(|m| m.0.clone()) else { return false };
- let h = world.resource_mut::<Assets<OwnMaterial>>().add(m);
+pub fn put(world: &mut World, e: Entity, h: Handle<OwnMaterial>) -> Result<(), String> {
+ let Some(std) = world.get::<MeshMaterial3d<StandardMaterial>>(e).map(|m| m.0.clone()) else { return Ok(()) };
world.entity_mut(e).remove::<MeshMaterial3d<StandardMaterial>>().insert((MeshMaterial3d(h), Shaded { std }, OwnSurface));
- true
+ // the frame's values a row gave before it was on
+ match world.entity_mut(e).take::<crate::own_live::Pending>() {
+ Some(p) => crate::own_live::patch(world, e, &p.0),
+ None => Ok(()),
+ }
}
#[cfg(test)]
diff --git a/systems/shader/src/own_live.rs b/systems/shader/src/own_live.rs
new file mode 100644
index 00000000..0fa4faea
--- /dev/null
+++ b/systems/shader/src/own_live.rs
@@ -0,0 +1,103 @@
+//! A Material's values over the frames (docs/control.feature FC2a): its uniforms and read-only storage buffers as the
+//! frame gives them. The rows send a part's <Material> uniforms and buffers as keyed `own:uniforms` component rows
+//! from each frame they change (raea-runtime-look own_uniforms), and `patch` packs them into the part's OwnMaterial
+//! and its ShaderBuffers, as Bevy's examples change a material's fields and buffers in their update systems
+//! (shader/storage_buffer's colours, sprite_material's dissolve).
+
+use bevy::prelude::*;
+use bevy::render::storage::ShaderBuffer;
+use bevy::shader::ShaderDefVal;
+use bevy::sprite_render::MeshMaterial2d;
+use serde_json::Value;
+
+use crate::layout;
+use crate::own::OwnMaterial;
+
+/// What a material's uniforms and buffers are packed from: its source as compiled (its struct types), its uniforms'
+/// and storage buffers' (name, WGSL type) in slot order, and its defs (a struct field under `@if`).
+#[derive(Debug)]
+pub struct Packing {
+ pub src: String,
+ pub uniforms: Vec<(String, String)>,
+ pub storages: Vec<(String, String)>,
+ pub defs: Vec<ShaderDefVal>,
+}
+
+/// A storage buffer's contents for its WGSL type, `array<T, N>` or `array<T>` with T an f32, u32 or i32 or a vec2-4
+/// of one: each element a number or [x, y(, z(, w))], in WGSL's storage layout (a vec3 takes 16 bytes, as a vec4).
+/// An empty one is 16 zero bytes (a binding can't be empty).
+pub fn storage(name: &str, ty: &str, v: &Value) -> Result<ShaderBuffer, String> {
+ let inner = ty.strip_prefix("array<").and_then(|t| t.strip_suffix('>')).ok_or_else(|| format!("storage buffer {name}: its type is array<T> or array<T, N>, got {ty} (the rest are FC2a's to come)"))?;
+ let el = match inner.rfind(',') {
+ Some(i) if inner[i + 1..].trim().parse::<u64>().is_ok() => inner[..i].trim(),
+ _ => inner.trim(),
+ };
+ let (k, n) = layout::kind(el).ok_or_else(|| format!("storage buffer {name}: its element {el} isn't f32, u32, i32 or a vec2/3/4 of one"))?;
+ let stride = if n == 1 { 1 } else if n == 2 { 2 } else { 4 };
+ let items = v.as_array().ok_or_else(|| format!("storage buffer {name} is a list of its elements, got {v}"))?;
+ let mut words = vec![0u32; (items.len() * stride).max(4)];
+ for (i, it) in items.iter().enumerate() {
+ let comps: Vec<f64> = match it {
+ Value::Array(a) => a.iter().filter_map(Value::as_f64).collect(),
+ x => x.as_f64().into_iter().collect(),
+ };
+ if comps.len() != n {
+ return Err(format!("storage buffer {name}: element {i} is {n} numbers ({el}), got {it}"));
+ }
+ for (c, x) in comps.iter().enumerate() {
+ words[i * stride + c] = layout::word(k, *x as f32);
+ }
+ }
+ Ok(ShaderBuffer::from(words))
+}
+
+/// The frame's values for a part whose Material isn't on yet, applied when it is (own.rs put).
+#[derive(Component)]
+pub struct Pending(pub Value);
+
+/// An `own:uniforms` component row: the frame's {uniforms, buffers} packed into the part's own Material (3D or 2D)
+/// and its storage buffers.
+pub fn patch(world: &mut World, e: Entity, v: &Value) -> Result<(), String> {
+ let h = world.get::<MeshMaterial3d<OwnMaterial>>(e).map(|m| m.0.clone()).or_else(|| world.get::<MeshMaterial2d<OwnMaterial>>(e).map(|m| m.0.clone()));
+ // a row applied before the part's Material is put on (shade_rows runs after the rows): kept for `put`
+ let Some(h) = h else {
+ world.entity_mut(e).insert(Pending(v.clone()));
+ return Ok(());
+ };
+ let Some((p, bufs)) = world.resource::<Assets<OwnMaterial>>().get(&h).map(|m| (m.packing.clone(), m.buffers())) else { return Err("own:uniforms: its Material isn't made".into()) };
+ if let Some(given) = v.get("uniforms").and_then(Value::as_object) {
+ let slots = layout::slots(&p.src, &p.uniforms, given, &p.defs)?;
+ if let Some(mut m) = world.resource_mut::<Assets<OwnMaterial>>().get_mut(&h) {
+ m.set_slots(slots);
+ }
+ }
+ let given = v.get("buffers").and_then(Value::as_object).cloned().unwrap_or_default();
+ for ((name, ty), b) in p.storages.iter().zip(bufs) {
+ let Some(x) = given.get(name) else { continue };
+ let sb = storage(name, ty, x)?;
+ if let Some(mut cur) = world.resource_mut::<Assets<ShaderBuffer>>().get_mut(&b) {
+ *cur = sb;
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn a_storage_buffer_is_laid_out_as_wgsl_stores_its_type() {
+ let words = |b: bevy::render::storage::ShaderBuffer| match b.data {
+ bevy::render::storage::ShaderBufferData::Initialized { data, .. } => data.chunks(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<_>>(),
+ _ => vec![],
+ };
+ let v = serde_json::json!([[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]]);
+ let w = words(super::storage("colors", "array<vec4<f32>, 5>", &v).unwrap());
+ assert_eq!(w[..8].iter().map(|x| f32::from_bits(*x)).collect::<Vec<_>>(), vec![1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0]);
+ // a vec3 takes 16 bytes; a u32 rounds
+ let w = words(super::storage("p", "array<vec3<f32>>", &serde_json::json!([[1, 2, 3], [4, 5, 6]])).unwrap());
+ assert_eq!(f32::from_bits(w[4]), 4.0);
+ assert_eq!(words(super::storage("n", "array<u32>", &serde_json::json!([2.6, 7])).unwrap())[..2], [3, 7]);
+ assert!(super::storage("p", "array<vec3<f32>>", &serde_json::json!([[1, 2]])).unwrap_err().contains("element 0"));
+ assert!(super::storage("m", "array<mat4x4<f32>>", &serde_json::json!([])).is_err());
+ }
+}
diff --git a/systems/shader/src/ui_bind.rs b/systems/shader/src/ui_bind.rs
index 1cd03593..c582fe67 100644
--- a/systems/shader/src/ui_bind.rs
+++ b/systems/shader/src/ui_bind.rs
@@ -11,6 +11,8 @@ pub const TEXTURES: usize = 4;
/// the 2D textures' at 17 and 19 (Bevy's view binds up to 8 of the fragment stage's 16).
pub const DIMS: [(&str, &str, usize); 5] = [("texture_1d<", "1d", 16), ("texture_2d_array<", "2d_array", 18), ("texture_cube<", "cube", 20), ("texture_cube_array<", "cube_array", 21), ("texture_3d<", "3d", 22)];
pub const SAMPLERS_WITH_DIMS: usize = 6;
+/// A Material's read-only storage buffers (`dims`), at 23 and 24.
+pub const STORAGE: [usize; 2] = [23, 24];
/// A UiMaterial source with its bindings renumbered: its uniforms (name, WGSL type) and its textures' names, each in
/// its slot's order, and how many samplers it binds.
@@ -21,6 +23,8 @@ pub struct Rebound {
pub textures: Vec<String>,
/// its textures of other dimensions (`dims`): each name and its dimension, "1d", "2d_array", "cube", ...
pub others: Vec<(String, &'static str)>,
+ /// its read-only storage buffers (`dims`): each name and WGSL type, in slot order
+ pub storages: Vec<(String, String)>,
pub samplers: usize,
}
@@ -35,6 +39,7 @@ pub fn rebind(src: &str) -> Result<Rebound, String> {
/// slots for (`what` names the material in errors).
pub fn rebind_in(src: &str, groups: &[&str], what: &str, dims: bool) -> Result<Rebound, String> {
let mut others: Vec<(String, &'static str)> = Vec::new();
+ let mut storages: Vec<(String, String)> = Vec::new();
let max_samplers = if dims { SAMPLERS_WITH_DIMS } else { TEXTURES };
let mut out = String::with_capacity(src.len());
let (mut uniforms, mut textures, mut samplers) = (Vec::new(), Vec::new(), 0usize);
@@ -57,12 +62,18 @@ pub fn rebind_in(src: &str, groups: &[&str], what: &str, dims: bool) -> Result<R
continue;
}
let decl = stmt.split_once("var").map(|(_, d)| d).ok_or_else(|| format!("{what}'s binding is a var, got {:?}", stmt.trim()))?;
- let (uniform, decl) = match decl.trim_start().strip_prefix("<uniform>") {
- Some(d) => (true, d),
- None => (false, decl),
- };
+ let d = decl.trim_start();
+ let space: String = d.strip_prefix('<').and_then(|r| r.split_once('>')).map(|(s, _)| s.chars().filter(|c| !c.is_whitespace()).collect()).unwrap_or_default();
+ let decl = if space.is_empty() { decl } else { &d[d.find('>').map_or(0, |i| i + 1)..] };
+ let uniform = space == "uniform";
+ if !space.is_empty() && !uniform && !(dims && (space == "storage" || space == "storage,read")) {
+ return Err(format!("{what}'s binding is a var<uniform>, a var<storage, read>, a texture or a sampler, got var<{space}> (the rest are FC2a's to come)"));
+ }
let (name, ty) = decl.split_once(':').map(|(n, t)| (n.trim().to_string(), t.trim().to_string())).ok_or_else(|| format!("{what}'s binding is `var NAME: TYPE`, got {:?}", stmt.trim()))?;
- let slot = if uniform {
+ let slot = if !space.is_empty() && !uniform {
+ storages.push((name.clone(), ty));
+ *STORAGE.get(storages.len() - 1).ok_or_else(|| format!("{what} binds at most {} storage buffers, {name} is one more", STORAGE.len()))?
+ } else if uniform {
uniforms.push((name.clone(), ty));
if uniforms.len() > UNIFORMS {
return Err(format!("{what} binds at most {UNIFORMS} uniforms, {name} is one more"));
@@ -97,7 +108,7 @@ pub fn rebind_in(src: &str, groups: &[&str], what: &str, dims: bool) -> Result<R
if samplers > textures.len() + others.len() {
return Err(format!("{what}'s samplers are its textures', one each: {samplers} samplers for {} textures", textures.len() + others.len()));
}
- Ok(Rebound { src: out, uniforms, textures, others, samplers })
+ Ok(Rebound { src: out, uniforms, textures, others, storages, samplers })
}
/// The group a declaration's `@group(N)` names.
diff --git a/systems/sprite/src/lib.rs b/systems/sprite/src/lib.rs
index f9d4c5f9..258cd023 100644
--- a/systems/sprite/src/lib.rs
+++ b/systems/sprite/src/lib.rs
@@ -167,8 +167,7 @@ pub fn spawn_shape(world: &mut World, e: Entity, t: &Tup, texture: Option<Handle
let spec: serde_json::Value = serde_json::from_str(s).map_err(|err| format!("shape2d {}: shader: {err}", t.id))?;
// its textures decoded now, as the shape's own picture is
let mut picture = |w: &mut World, p: &serde_json::Value| p.as_str().ok_or_else(|| format!("a texture is a picture's path, got {p}")).and_then(|p| raea_sys_shader::own::picture(w, p));
- let m = raea_sys_shader::own::build(world, &spec, &mut picture, true).map_err(|err| format!("shape2d {}: {err}", t.id))?;
- let m = world.resource_mut::<Assets<raea_sys_shader::own::OwnMaterial>>().add(m);
+ let m = raea_sys_shader::own::shared(world, &spec, &mut picture, true).map_err(|err| format!("shape2d {}: {err}", t.id))?;
world.entity_mut(e).insert(MeshMaterial2d(m));
return Ok(());
}