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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
FC2d: a mesh drawn many times in one draw by your shader; shader_advanced/custom_shader_instancing passes
shinyobjectzbe388ffe807d
diff --git a/bench/bevy-parity/examples.list b/bench/bevy-parity/examples.listindex 953a998a..a2e31d0e 100644--- a/bench/bevy-parity/examples.list+++ b/bench/bevy-parity/examples.list@@ -144,3 +144,4 @@ shader_advanced/custom_post_processingshader_advanced/custom_vertex_attributeshader_advanced/fullscreen_materialshader_advanced/custom_render_phase+shader_advanced/custom_shader_instancingdiff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsvindex 81bd6344..17d91ec0 100644--- a/bench/bevy-parity/runs.tsv+++ b/bench/bevy-parity/runs.tsv@@ -143,3 +143,4 @@ shader_advanced/custom_post_processing - 10,30,60shader_advanced/custom_vertex_attribute - 5,10shader_advanced/fullscreen_material - 10,30,60shader_advanced/custom_render_phase - 5,10+shader_advanced/custom_shader_instancing - 5,10diff --git a/docs/bevy-parity.md b/docs/bevy-parity.mdindex 3d0612f5..850589be 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 andframe time at most 1.25x the example's). Wall time is one machine's, measured in the same run.-Examples: **438**, ported **144**, passing **144**, excluded **17** (docs/bevy-parity/excluded.tsv), left **277**.+Examples: **438**, ported **145**, passing **145**, excluded **17** (docs/bevy-parity/excluded.tsv), left **276**.raea's frame ms is its update's plus the time React takes to step a frame for its 3D (step), which the exampledoesn't pay.@@ -230,10 +230,12 @@ doesn't pay.| shader_advanced/fullscreen_material | 10 | 0.999748 | 6 | 1 / 1 | 444 / 522 | 6 / 8 | 2 / 2 | 23.02 / 0.953 = 0.953 + 0 | yes | || shader_advanced/fullscreen_material | 30 | 0.999749 | 6 | 1 / 1 | 444 / 522 | 6 / 8 | 2 / 2 | 1.521 / 0.746 = 0.746 + 0 | yes | || shader_advanced/fullscreen_material | 60 | 0.999749 | 6 | 1 / 1 | 444 / 522 | 6 / 8 | 2 / 2 | 1.584 / 0.658 = 0.658 + 0 | yes | |-| shader_advanced/custom_render_phase | 10 | 1.000000 | 0 | 3 / 3 | 445 / 529 | 8 / 10 | 4 / 4 | 3.461 / 1.979 = 1.979 + 0 | yes | |-| shader_advanced/custom_render_phase | 5 | 1.000000 | 0 | 3 / 3 | 445 / 529 | 8 / 10 | 4 / 4 | 62.92 / 5.261 = 5.261 + 0 | yes | |-| shader_advanced/custom_phase_item | 10 | 1.000000 | 0 | 0 / 0 | 442 / 522 | 5 / 7 | 1 / 1 | 2.263 / 0.98 = 0.98 + 0 | yes | |-| shader_advanced/custom_phase_item | 5 | 1.000000 | 0 | 0 / 0 | 442 / 522 | 5 / 7 | 1 / 1 | 39.678 / 2.388 = 2.388 + 0 | yes | |+| shader_advanced/custom_render_phase | 10 | 1.000000 | 0 | 3 / 3 | 445 / 530 | 8 / 10 | 4 / 4 | 3.024 / 2.523 = 2.523 + 0 | yes | |+| shader_advanced/custom_render_phase | 5 | 1.000000 | 0 | 3 / 3 | 445 / 530 | 8 / 10 | 4 / 4 | 50.318 / 4.435 = 4.435 + 0 | yes | |+| shader_advanced/custom_shader_instancing | 10 | 1.000000 | 0 | 0 / 0 | 442 / 524 | 6 / 8 | 1 / 1 | 2.352 / 2.528 = 2.528 + 0 | yes | |+| shader_advanced/custom_shader_instancing | 5 | 1.000000 | 0 | 0 / 0 | 442 / 524 | 6 / 8 | 1 / 1 | 45.771 / 4.077 = 4.077 + 0 | yes | |+| shader_advanced/custom_phase_item | 10 | 1.000000 | 0 | 0 / 0 | 442 / 523 | 5 / 7 | 1 / 1 | 4.21 / 1.445 = 1.445 + 0 | yes | |+| shader_advanced/custom_phase_item | 5 | 1.000000 | 0 | 0 / 0 | 442 / 523 | 5 / 7 | 1 / 1 | 54.956 / 2.448 = 2.448 + 0 | yes | |## Excludeddiff --git a/docs/bevy-parity/results.jsonl b/docs/bevy-parity/results.jsonlindex 4f6f131c..d12e7995 100644--- a/docs/bevy-parity/results.jsonl+++ b/docs/bevy-parity/results.jsonl@@ -217,7 +217,9 @@{"example":"shader_advanced/fullscreen_material","frame":10,"ssim":0.999748,"tile":6,"bevy":{"batch_keys":1,"entities":444,"extents":["0.5000 0.5000 0.5000"],"frame":10,"frame_ms":23.02,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":17,"entities":522,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.5000 0.5000 0.5000"],"frame_ms":0.953,"step_ms":null,"cost_ms":0.953},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}{"example":"shader_advanced/fullscreen_material","frame":30,"ssim":0.999749,"tile":6,"bevy":{"batch_keys":1,"entities":444,"extents":["0.5000 0.5000 0.5000"],"frame":30,"frame_ms":1.521,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":37,"entities":522,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.5000 0.5000 0.5000"],"frame_ms":0.746,"step_ms":null,"cost_ms":0.746},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}{"example":"shader_advanced/fullscreen_material","frame":60,"ssim":0.999749,"tile":6,"bevy":{"batch_keys":1,"entities":444,"extents":["0.5000 0.5000 0.5000"],"frame":60,"frame_ms":1.584,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":67,"entities":522,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.5000 0.5000 0.5000"],"frame_ms":0.658,"step_ms":null,"cost_ms":0.658},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}-{"example":"shader_advanced/custom_render_phase","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":3,"entities":445,"extents":["0.4972 0.5000 0.5000","0.5000 0.5000 0.5000","4.0000 4.0000 0.0000"],"frame":10,"frame_ms":3.461,"materials":4,"mesh_entities":3,"meshes":8,"other_material":0,"visible":3},"raea":{"frame":17,"entities":529,"mesh_entities":3,"visible":3,"meshes":10,"materials":4,"batch_keys":3,"other_material":0,"extents":["0.4972 0.5000 0.5000","0.5000 0.5000 0.5000","4.0000 4.0000 0.0000"],"frame_ms":1.979,"step_ms":null,"cost_ms":1.979},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}-{"example":"shader_advanced/custom_render_phase","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":3,"entities":445,"extents":["0.4972 0.5000 0.5000","0.5000 0.5000 0.5000","4.0000 4.0000 0.0000"],"frame":5,"frame_ms":62.92,"materials":4,"mesh_entities":3,"meshes":8,"other_material":0,"visible":3},"raea":{"frame":12,"entities":529,"mesh_entities":3,"visible":3,"meshes":10,"materials":4,"batch_keys":3,"other_material":0,"extents":["0.4972 0.5000 0.5000","0.5000 0.5000 0.5000","4.0000 4.0000 0.0000"],"frame_ms":5.261,"step_ms":null,"cost_ms":5.261},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}-{"example":"shader_advanced/custom_phase_item","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":10,"frame_ms":2.263,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":522,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":0.98,"step_ms":null,"cost_ms":0.98},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}-{"example":"shader_advanced/custom_phase_item","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":5,"frame_ms":39.678,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":12,"entities":522,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.388,"step_ms":null,"cost_ms":2.388},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/custom_render_phase","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":3,"entities":445,"extents":["0.4972 0.5000 0.5000","0.5000 0.5000 0.5000","4.0000 4.0000 0.0000"],"frame":10,"frame_ms":3.024,"materials":4,"mesh_entities":3,"meshes":8,"other_material":0,"visible":3},"raea":{"frame":17,"entities":530,"mesh_entities":3,"visible":3,"meshes":10,"materials":4,"batch_keys":3,"other_material":0,"extents":["0.4972 0.5000 0.5000","0.5000 0.5000 0.5000","4.0000 4.0000 0.0000"],"frame_ms":2.523,"step_ms":null,"cost_ms":2.523},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/custom_render_phase","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":3,"entities":445,"extents":["0.4972 0.5000 0.5000","0.5000 0.5000 0.5000","4.0000 4.0000 0.0000"],"frame":5,"frame_ms":50.318,"materials":4,"mesh_entities":3,"meshes":8,"other_material":0,"visible":3},"raea":{"frame":12,"entities":530,"mesh_entities":3,"visible":3,"meshes":10,"materials":4,"batch_keys":3,"other_material":0,"extents":["0.4972 0.5000 0.5000","0.5000 0.5000 0.5000","4.0000 4.0000 0.0000"],"frame_ms":4.435,"step_ms":null,"cost_ms":4.435},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/custom_shader_instancing","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":10,"frame_ms":2.352,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":17,"entities":524,"mesh_entities":1,"visible":1,"meshes":8,"materials":1,"batch_keys":0,"other_material":1,"extents":[],"frame_ms":2.528,"step_ms":null,"cost_ms":2.528},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/custom_shader_instancing","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":5,"frame_ms":45.771,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":12,"entities":524,"mesh_entities":1,"visible":1,"meshes":8,"materials":1,"batch_keys":0,"other_material":1,"extents":[],"frame_ms":4.077,"step_ms":null,"cost_ms":4.077},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/custom_phase_item","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":10,"frame_ms":4.21,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":523,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.445,"step_ms":null,"cost_ms":1.445},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/custom_phase_item","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":5,"frame_ms":54.956,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":12,"entities":523,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.448,"step_ms":null,"cost_ms":2.448},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}diff --git a/sdk/raea/bench/bevy-parity/shader_advanced/custom_shader_instancing.tsx b/sdk/raea/bench/bevy-parity/shader_advanced/custom_shader_instancing.tsxnew file mode 100644index 00000000..43a3efeb--- /dev/null+++ b/sdk/raea/bench/bevy-parity/shader_advanced/custom_shader_instancing.tsx@@ -0,0 +1,45 @@+// Bevy v0.20.0 examples/shader_advanced/custom_shader_instancing.rs in raea's TSX (docs/control.feature FC2d): one+// Cuboid of 0.5 m drawn 100 times in one draw by assets/shaders/instancing.wesl as written, in the camera's+// Transparent3d phase: a <ShaderInstances> whose instance buffer holds each InstanceData (a position vec3 and scale+// f32 read at location 3, a colour [f32; 4] at location 4: 32 bytes). Instance (x, y) for x and y in 0.1 to 1.0 is at+// (10x - 5, 10y - 5, 0), scale 1, coloured LinearRgba::from(Color::hsla(360x, y, 0.5, 1)). The mesh has no material+// (Bevy's entity is only Mesh3d, the instances and NoFrustumCulling), so it draws only through its instances. The+// camera at (0, 0, 15) looking at the origin, in Bevy's default 1280 x 720 window (its NoIndirectDrawing isn't reflected,+// and raea's draw of the instances is direct either way, as the example's DrawMeshInstanced is).+import { Composition, registerRoot, staticFile } from "raea";+import { BevyComponent, Entity, ShaderInstances } from "raea/3d";+import { Camera3d } from "raea/camera";+import { Hsla, LinearRgba } from "raea/color";+import { Transform } from "raea/transform";++const f = Math.fround;++// InstanceData for x in 1..=10, then y in 1..=10 (the example's flat_map order)+const WORDS: number[] = [];+for (let i = 1; i <= 10; i++) {+ for (let j = 1; j <= 10; j++) {+ const [x, y] = [f(i / 10), f(j / 10)];+ const c = LinearRgba.from(new Hsla(f(x * 360), y, 0.5, 1).to_srgba());+ WORDS.push(f(f(x * 10) - 5), f(f(y * 10) - 5), 0, 1, c.red, c.green, c.blue, c.alpha);+ }+}++function Shot() {+ return (+ <>+ <Entity>+ <BevyComponent type="bevy_mesh::components::Mesh3d" value={{ primitive: "Cuboid", half_size: [0.25, 0.25, 0.25] }} />+ <BevyComponent type="bevy_camera::visibility::NoFrustumCulling" value={{}} />+ <ShaderInstances+ shader={staticFile("shaders/instancing.wesl")}+ stride={32}+ attributes={[{ format: "Float32x4", offset: 0, location: 3 }, { format: "Float32x4", offset: 16, location: 4 }]}+ words={WORDS}+ />+ </Entity>+ <Camera3d transform={Transform.fromXyz(0, 0, 15).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/render/src/3d.tsx b/sdk/render/src/3d.tsxindex 4fae5fe8..5475f9e1 100644--- a/sdk/render/src/3d.tsx+++ b/sdk/render/src/3d.tsx@@ -2,8 +2,8 @@// carries its name (data-3d) and props (data-props, JSON) for Bevy to draw; a Mesh also carries its Manifold// expression (data-shape). Engine-safe: this module imports nothing beyond React.import { toHex } from "./colour";-export { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, SurfaceShader, ThreeShaderMaterial, surfaceShader, samplerSpec, FramePass, Compute, PhaseItem, MeshPass, MeshVertexAttribute, ATTRIBUTE_POSITION, ATTRIBUTE_NORMAL, ATTRIBUTE_UV_0, ATTRIBUTE_UV_1, ATTRIBUTE_TANGENT, ATTRIBUTE_COLOR, Atmosphere, eulerOf, Entity, Refinish, clipEvents, Model, ImagePlane, surfaceTurn, Decal, Plate, Bloom, Fog, ToneMapping, Grade, Environment, EnvironmentMapLight, Skybox, AmbientOcclusion, AntiAliasing, Shadows, VolumetricFog, FogVolume, Fire, dofOf, DepthOfField, Outline, Fisheye, LensDistortion, MotionBlur, checkPass, Look, Scene, Entities, BevyComponent, Gizmo, ShaderMesh, BevyResource, Span, RichText, Instances, scatter, Grass } from "./3d/all";-export type { Vec3, Canvas3DProps, CuboidProps, SphereProps, CylinderProps, TorusProps, Plane3dProps, ConeProps, CapsuleProps, Capsule3dProps, BufferMeshProps, Text3DProps, Animate3d, SurfaceDrawProps, ToonBand, ToonRim, ToonHighlight, ToonOutline, SurfaceShaderSpec, ThreeShaderMaterialProps, ThreeUniform, SamplerSpec, SamplerWrap, FramePassProps, ComputeProps, MeshSlab, PhaseItemProps, PhaseAttribute, MeshPassProps, VertexFormat, MeshAttribute, AtmosphereProps, BevyParts, EntityProps, ModelProps, AnimGraphNode, ImagePlaneProps, DecalProps, PlateProps, BloomProps, FogProps, FogColor, FogFalloff, ToneMappingProps, GradeSection, GradeProps, EnvironmentProps, EnvironmentMapLightProps, SkyboxProps, AmbientOcclusionProps, AntiAliasingProps, ShadowsProps, VolumetricFogProps, FogVolumeProps, FireProps, DepthOfFieldProps, OutlineProps, LensCommon, FisheyeProps, LensDistortionProps, MotionBlurProps, LookProps, LookPass, SceneProps, BevyComponentProps, GizmoProps, ShaderMeshProps, SpanProps, GlyphInfo, GlyphStyle, RichTextProps, Instance, InstancesProps, PlanBox, ScatterOptions, GrassProps, GrassLod } from "./3d/all";+export { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, SurfaceShader, ThreeShaderMaterial, surfaceShader, samplerSpec, FramePass, Compute, PhaseItem, MeshPass, ShaderInstances, MeshVertexAttribute, ATTRIBUTE_POSITION, ATTRIBUTE_NORMAL, ATTRIBUTE_UV_0, ATTRIBUTE_UV_1, ATTRIBUTE_TANGENT, ATTRIBUTE_COLOR, Atmosphere, eulerOf, Entity, Refinish, clipEvents, Model, ImagePlane, surfaceTurn, Decal, Plate, Bloom, Fog, ToneMapping, Grade, Environment, EnvironmentMapLight, Skybox, AmbientOcclusion, AntiAliasing, Shadows, VolumetricFog, FogVolume, Fire, dofOf, DepthOfField, Outline, Fisheye, LensDistortion, MotionBlur, checkPass, Look, Scene, Entities, BevyComponent, Gizmo, ShaderMesh, BevyResource, Span, RichText, Instances, scatter, Grass } from "./3d/all";+export type { Vec3, Canvas3DProps, CuboidProps, SphereProps, CylinderProps, TorusProps, Plane3dProps, ConeProps, CapsuleProps, Capsule3dProps, BufferMeshProps, Text3DProps, Animate3d, SurfaceDrawProps, ToonBand, ToonRim, ToonHighlight, ToonOutline, SurfaceShaderSpec, ThreeShaderMaterialProps, ThreeUniform, SamplerSpec, SamplerWrap, FramePassProps, ComputeProps, MeshSlab, PhaseItemProps, PhaseAttribute, MeshPassProps, ShaderInstancesProps, VertexFormat, MeshAttribute, AtmosphereProps, BevyParts, EntityProps, ModelProps, AnimGraphNode, ImagePlaneProps, DecalProps, PlateProps, BloomProps, FogProps, FogColor, FogFalloff, ToneMappingProps, GradeSection, GradeProps, EnvironmentProps, EnvironmentMapLightProps, SkyboxProps, AmbientOcclusionProps, AntiAliasingProps, ShadowsProps, VolumetricFogProps, FogVolumeProps, FireProps, DepthOfFieldProps, OutlineProps, LensCommon, FisheyeProps, LensDistortionProps, MotionBlurProps, LookProps, LookPass, SceneProps, BevyComponentProps, GizmoProps, ShaderMeshProps, SpanProps, GlyphInfo, GlyphStyle, RichTextProps, Instance, InstancesProps, PlanBox, ScatterOptions, GrassProps, GrassLod } from "./3d/all";export { CrossSection, crossSection, manifold, outline, Solid, type Bounds, type Polygons, type Section } from "./solid";// blended distance fields and generated growth (trees, lofts, terrain, boulders, rosettes), as Solids (grow.ts)diff --git a/sdk/render/src/3d/phase.tsx b/sdk/render/src/3d/phase.tsxindex 10b97ded..4f2c722e 100644--- a/sdk/render/src/3d/phase.tsx+++ b/sdk/render/src/3d/phase.tsx@@ -64,3 +64,28 @@ export function MeshPass(p: MeshPassProps) {if (typeof shader !== "string" || !shader) throw new TypeError(`MeshPass: shader is a shader file, staticFile("shaders/x.wesl"), got ${JSON.stringify(shader)}`);return <BevyComponent type="raea_sys_phase::MeshPass" value={{ shader: assetPath(shader), vertex, fragment }} />;}++export interface ShaderInstancesProps {+ /** the shader file, compiled as written: staticFile("shaders/x.wesl"). Its vertex reads the mesh's position, normal+ * and uv at locations 0 to 2 and the instance's attributes at theirs; its bind groups are Bevy's mesh pipeline's */+ shader: string;+ /** each instance's bytes (a multiple of 4) */+ stride: number;+ /** what the shader reads of an instance: Bevy's VertexFormat, its byte offset and @location (3 and up) */+ attributes: PhaseAttribute[];+ /** every instance's 32-bit words in order, `stride / 4` of them each */+ words: number[];+}++/** The mesh it's inside drawn once per instance in one draw, by your shader, in the camera's Transparent3d phase, a+ * vertex buffer of your words stepped per instance (Bevy's shader_advanced/custom_shader_instancing). Its instances+ * aren't in the mesh's bounds: give the mesh Bevy's NoFrustumCulling (<BevyComponent type="bevy_camera::visibility::NoFrustumCulling" value={{}} />).+ * @bevy raea_sys_phase::ShaderInstances */+export function ShaderInstances(p: ShaderInstancesProps) {+ const { shader, stride, attributes, words } = p;+ if (typeof shader !== "string" || !shader) throw new TypeError(`ShaderInstances: shader is a shader file, staticFile("shaders/x.wesl"), got ${JSON.stringify(shader)}`);+ if (!Number.isInteger(stride) || stride < 4 || stride % 4 !== 0) throw new TypeError(`ShaderInstances: stride is an instance's bytes, a multiple of 4, got ${stride}`);+ if (!Array.isArray(words) || words.length % (stride / 4) !== 0 || !words.every(Number.isFinite)) throw new TypeError(`ShaderInstances: words are each instance's ${stride / 4} numbers, got ${words?.length}`);+ for (const a of attributes) if (!(Number.isInteger(a.offset) && a.offset >= 0 && a.offset < stride && Number.isInteger(a.location) && a.location >= 0)) throw new TypeError(`ShaderInstances: an attribute is { format, offset (under the stride), location }, got ${JSON.stringify(a)}`);+ return <BevyComponent type="raea_sys_phase::ShaderInstances" value={{ shader: assetPath(shader), stride, attributes, words }} />;+}diff --git a/systems/phase/src/draw.rs b/systems/phase/src/draw.rsindex f0d1aa6a..04e0f5fc 100644--- a/systems/phase/src/draw.rs+++ b/systems/phase/src/draw.rs@@ -63,7 +63,7 @@ fn prepare(mut commands: Commands, device: Res<RenderDevice>, items: Query<(Enti}}-fn vertex_format(f: &str) -> Option<VertexFormat> {+pub(crate) fn vertex_format(f: &str) -> Option<VertexFormat> {use VertexFormat::*;Some(match f {"Float32" => Float32,@@ -83,6 +83,16 @@ fn vertex_format(f: &str) -> Option<VertexFormat> {})}+/// Whether any of `attributes` has a format that isn't one of Bevy's VertexFormats here.+pub(crate) fn unknown_format(attributes: &[crate::PhaseAttribute]) -> bool {+ for a in attributes {+ if vertex_format(&a.format).is_none() {+ return true;+ }+ }+ false+}+fn compare(c: &str) -> Option<CompareFunction> {use CompareFunction::*;Some(match c {diff --git a/systems/phase/src/instances.rs b/systems/phase/src/instances.rsnew file mode 100644index 00000000..f472b082--- /dev/null+++ b/systems/phase/src/instances.rs@@ -0,0 +1,183 @@+//! A mesh drawn many times in one draw by your shader (docs/control.feature FC2d), as Bevy's+//! shader_advanced/custom_shader_instancing draws its cubes: a Mesh3d entity with ShaderInstances is drawn in each+//! view's Transparent3d phase by Bevy's mesh pipeline with its vertex and fragment shader swapped for your file as+//! written, and a second vertex buffer of your words stepped per instance (laid out as its `attributes` say: locations+//! after the mesh's position, normal and uv at 0 to 2), once per instance of `stride` bytes.++use bevy::core_pipeline::core_3d::{Transparent3d, TransparentSortingInfo3d};+use bevy::ecs::system::lifetimeless::{Read, SRes};+use bevy::ecs::system::SystemParamItem;+use bevy::mesh::{MeshVertexBufferLayoutRef, VertexBufferLayout};+use bevy::pbr::{self, MeshInputUniform, MeshPipeline, MeshPipelineKey, MeshUniform, RenderMeshInstances, SetMeshBindGroup, SetMeshViewBindGroup, SetMeshViewBindingArrayBindGroup, ViewKeyCache};+use bevy::prelude::*;+use bevy::render::batching::gpu_preprocessing::BatchedInstanceBuffers;+use bevy::render::extract_component::{ExtractComponent, ExtractComponentPlugin};+use bevy::render::mesh::allocator::MeshAllocator;+use bevy::render::mesh::{RenderMesh, RenderMeshBufferInfo};+use bevy::render::render_asset::RenderAssets;+use bevy::render::render_phase::{AddRenderCommand, DrawFunctions, PhaseItem, PhaseItemExtraIndex, RenderCommand, RenderCommandResult, SetItemPipeline, TrackedRenderPass, ViewSortedRenderPhases};+use bevy::render::render_resource::*;+use bevy::render::renderer::RenderDevice;+use bevy::render::sync_world::MainEntity;+use bevy::render::view::ExtractedView;+use bevy::render::{Render, RenderApp, RenderSystems};++use crate::PhaseAttribute;++/// A mesh's instances: your shader file (as written), and each instance's `stride` bytes of 32-bit words, read as its+/// `attributes` say.+#[derive(Component, Clone, Debug, Default, Reflect, ExtractComponent)]+#[extract_app(RenderApp)]+#[reflect(Component, Default)]+#[type_path = "raea_sys_phase"]+pub struct ShaderInstances {+ pub shader: String,+ pub stride: u64,+ pub attributes: Vec<PhaseAttribute>,+ pub words: Vec<f32>,+ /// its shader file, registered as written (raea-sys-shader), and the id register gave it+ #[reflect(ignore)]+ pub registered: Option<(String, u128)>,+}++pub fn install(app: &mut App) {+ app.register_type::<ShaderInstances>();+ app.add_systems(PostUpdate, crate::register::<ShaderInstances>);+ app.add_plugins(ExtractComponentPlugin::<ShaderInstances>::default());+ let Some(r) = app.get_sub_app_mut(RenderApp) else { return };+ r.add_render_command::<Transparent3d, DrawInstances>()+ .init_resource::<SpecializedMeshPipelines<InstancesPipeline>>()+ .add_systems(Render, (queue.in_set(RenderSystems::QueueMeshes), prepare.in_set(RenderSystems::PrepareResources)));+}++/// The instances' buffer on the GPU, and the words it was made from.+#[derive(Component)]+pub struct InstanceBuffer {+ buffer: Buffer,+ count: u32,+ made: Vec<f32>,+}++fn prepare(mut commands: Commands, device: Res<RenderDevice>, items: Query<(Entity, &ShaderInstances, Option<&InstanceBuffer>)>) {+ for (e, s, had) in &items {+ if s.stride == 0 || had.is_some_and(|b| b.made == s.words) {+ continue;+ }+ let buffer = device.create_buffer_with_data(&BufferInitDescriptor { label: Some("raea_shader_instances"), contents: bytemuck::cast_slice(&s.words), usage: BufferUsages::VERTEX | BufferUsages::COPY_DST });+ let count = (s.words.len() as u64 * 4 / s.stride) as u32;+ commands.entity(e).insert(InstanceBuffer { buffer, count, made: s.words.clone() });+ }+}++#[derive(Resource)]+pub struct InstancesPipeline {+ pub(crate) mesh: MeshPipeline,+}++/// A variant: the view and mesh's key, the shader, and the instance buffer's layout.+#[derive(Clone, Hash, PartialEq, Eq)]+pub struct InstancesKey {+ mesh: MeshPipelineKey,+ shader: u128,+ stride: u64,+ attributes: Vec<(String, u64, u32)>,+}++impl SpecializedMeshPipeline for InstancesPipeline {+ type Key = InstancesKey;++ fn specialize(&self, key: InstancesKey, layout: &MeshVertexBufferLayoutRef) -> Result<RenderPipelineDescriptor, SpecializedMeshPipelineError> {+ let mut d = self.mesh.specialize(key.mesh, layout)?;+ let shader = Handle::Uuid(bevy::asset::uuid::Uuid::from_u128(key.shader), core::marker::PhantomData);+ let attributes = key.attributes.iter().map(|(f, offset, location)| VertexAttribute { format: crate::draw::vertex_format(f).unwrap_or(VertexFormat::Float32x4), offset: *offset, shader_location: *location }).collect();+ d.vertex.shader = shader.clone();+ d.vertex.buffers.push(VertexBufferLayout { array_stride: key.stride, step_mode: VertexStepMode::Instance, attributes });+ if let Some(f) = d.fragment.as_mut() {+ f.shader = shader;+ }+ Ok(d)+ }+}++type DrawInstances = (SetItemPipeline, SetMeshViewBindGroup<0>, SetMeshViewBindingArrayBindGroup<1>, SetMeshBindGroup<2>, DrawMeshInstanced);++/// Each mesh with ShaderInstances (and a shader registered) queued in every view's Transparent3d phase.+#[allow(clippy::too_many_arguments)]+fn queue(+ draws: Res<DrawFunctions<Transparent3d>>,+ pipeline: Res<InstancesPipeline>,+ mut pipelines: ResMut<SpecializedMeshPipelines<InstancesPipeline>>,+ cache: Res<PipelineCache>,+ meshes: Res<RenderAssets<RenderMesh>>,+ instances: Res<RenderMeshInstances>,+ batched: Option<Res<BatchedInstanceBuffers<MeshUniform, MeshInputUniform>>>,+ items: Query<(Entity, &MainEntity, &ShaderInstances)>,+ mut phases: ResMut<ViewSortedRenderPhases<Transparent3d>>,+ views: Query<&ExtractedView>,+ keys: Res<ViewKeyCache>,+) {+ let draw = draws.read().id::<DrawInstances>();+ for view in &views {+ let Some(phase) = phases.get_mut(&view.retained_view_entity) else { continue };+ let Some(&view_key) = keys.get(&view.retained_view_entity) else { continue };+ for (entity, main, s) in &items {+ let (Some(shader), Some(instance)) = (s.registered.as_ref().map(|r| r.1), instances.render_mesh_queue_data(*main)) else { continue };+ let Some(mesh) = meshes.get(instance.mesh_asset_id()) else { continue };+ if crate::draw::unknown_format(&s.attributes) {+ error!("ShaderInstances: an attribute's format isn't Bevy's VertexFormat (Float32x4, Uint32, ...)");+ continue;+ }+ let key = InstancesKey {+ mesh: view_key | MeshPipelineKey::from_primitive_topology_and_strip_index(mesh.primitive_topology(), mesh.index_format()),+ shader,+ stride: s.stride,+ attributes: s.attributes.iter().map(|a| (a.format.clone(), a.offset, a.location)).collect(),+ };+ let id = match pipelines.specialize(&cache, &pipeline, key, &mesh.layout) {+ Ok(id) => id,+ Err(err) => {+ error!("ShaderInstances: {err}");+ continue;+ }+ };+ let centre = pbr::get_mesh_instance_world_from_local(*main, instance.current_uniform_index, &instances, batched.as_deref()).transform_point3(mesh.aabb_center);+ phase.add_retained(Transparent3d {+ sorting_info: TransparentSortingInfo3d::Sorted { mesh_center: centre, depth_bias: 0.0 },+ entity: (entity, *main),+ pipeline: id,+ draw_function: draw,+ distance: 0.0,+ batch_range: 0..1,+ extra_index: PhaseItemExtraIndex::None,+ indexed: true,+ });+ }+ }+}++/// The mesh's vertex buffer and the instances' buffer bound, and the mesh drawn once per instance.+pub struct DrawMeshInstanced;++impl<P: PhaseItem> RenderCommand<P> for DrawMeshInstanced {+ type Param = (SRes<RenderAssets<RenderMesh>>, SRes<RenderMeshInstances>, SRes<MeshAllocator>);+ type ViewQuery = ();+ type ItemQuery = Read<InstanceBuffer>;++ fn render<'w>(item: &P, _: (), buffer: Option<&'w InstanceBuffer>, (meshes, instances, allocator): SystemParamItem<'w, '_, Self::Param>, pass: &mut TrackedRenderPass<'w>) -> RenderCommandResult {+ let allocator = allocator.into_inner();+ let Some(instance) = instances.render_mesh_queue_data(item.main_entity()) else { return RenderCommandResult::Skip };+ let Some(gpu) = meshes.into_inner().get(instance.mesh_asset_id()) else { return RenderCommandResult::Skip };+ let (Some(buffer), Some(vertices)) = (buffer, allocator.mesh_vertex_slice(&instance.mesh_asset_id())) else { return RenderCommandResult::Skip };+ pass.set_vertex_buffer(0, vertices.buffer.slice(..));+ pass.set_vertex_buffer(1, buffer.buffer.slice(..));+ match &gpu.buffer_info {+ RenderMeshBufferInfo::Indexed { index_format, count } => {+ let Some(indices) = allocator.mesh_index_slice(&instance.mesh_asset_id()) else { return RenderCommandResult::Skip };+ pass.set_index_buffer(indices.buffer.slice(..), *index_format);+ pass.draw_indexed(indices.range.start..indices.range.start + count, vertices.range.start as i32, 0..buffer.count);+ }+ RenderMeshBufferInfo::NonIndexed => pass.draw(vertices.range, 0..buffer.count),+ }+ RenderCommandResult::Success+ }+}diff --git a/systems/phase/src/lib.rs b/systems/phase/src/lib.rsindex b36e41be..58c396b6 100644--- a/systems/phase/src/lib.rs+++ b/systems/phase/src/lib.rs@@ -3,7 +3,9 @@//! its shader file as written, its `vertex` and `fragment` entry points, reading its own vertex buffer (laid out as//! its `attributes` say) and index buffer. <PhaseItem> in raea's TSX gives an <Entity> the component; draw.rs queues,//! prepares and draws it. A MeshPass on a Mesh3d entity draws that mesh again by its own shader in a phase after the-//! main opaque pass, as Bevy's shader_advanced/custom_render_phase draws its stencil (mesh_pass.rs).+//! main opaque pass, as Bevy's shader_advanced/custom_render_phase draws its stencil (mesh_pass.rs), and+//! ShaderInstances draws it many times in one draw, a vertex buffer of yours stepped per instance+//! (shader_advanced/custom_shader_instancing, instances.rs).use bevy::camera::visibility::{self, VisibilityClass};use bevy::prelude::*;@@ -11,8 +13,10 @@ use bevy::render::extract_component::{ExtractComponent, ExtractComponentPlugin};use bevy::render::RenderApp;mod draw;+mod instances;mod mesh_pass;+pub use instances::ShaderInstances;pub use mesh_pass::MeshPass;/// A vertex attribute: its format (Bevy's VertexFormat by name, "Float32x3"), byte offset and shader location.@@ -71,7 +75,7 @@ macro_rules! shaded {})*};}-shaded!(PhaseItem: "PhaseItem", MeshPass: "MeshPass");+shaded!(PhaseItem: "PhaseItem", MeshPass: "MeshPass", ShaderInstances: "ShaderInstances");/// Each new or changed `C`'s shader file read and registered as written (a file it can't read is logged).pub(crate) fn register<C: Shaded>(world: &mut World) {@@ -95,10 +99,20 @@ pub(crate) fn register<C: Shaded>(world: &mut World) {}}+/// The mesh pass's and the instances' pipelines, each Bevy's mesh pipeline under its own specialize.+fn pipelines(mut commands: Commands, mesh: Res<bevy::pbr::MeshPipeline>) {+ commands.insert_resource(mesh_pass::PassPipeline { mesh: mesh.clone() });+ commands.insert_resource(instances::InstancesPipeline { mesh: mesh.clone() });+}+pub fn install(app: &mut App) {app.register_type::<PhaseItem>();app.add_systems(PostUpdate, register::<PhaseItem>);app.add_plugins(ExtractComponentPlugin::<PhaseItem>::default());draw::install(app);mesh_pass::install(app);+ instances::install(app);+ if let Some(r) = app.get_sub_app_mut(bevy::render::RenderApp) {+ r.add_systems(bevy::render::RenderStartup, pipelines.after(bevy::pbr::MeshPipelineSystems));+ }}diff --git a/systems/phase/src/mesh_pass.rs b/systems/phase/src/mesh_pass.rsindex 6655692c..ea0fc24d 100644--- a/systems/phase/src/mesh_pass.rs+++ b/systems/phase/src/mesh_pass.rs@@ -16,7 +16,7 @@ use bevy::ecs::system::lifetimeless::SRes;use bevy::ecs::system::SystemParamItem;use bevy::math::FloatOrd;use bevy::mesh::{MeshAttributeCompressionFlags, MeshVertexBufferLayoutRef};-use bevy::pbr::{self, DrawMesh, MeshInputUniform, MeshPipeline, MeshPipelineKey, MeshPipelineSystems, MeshPipelineViewLayoutKey, MeshUniform, RenderMeshInstances, SetMeshBindGroup, SetMeshViewBindGroup, SetMeshViewEmptyBindGroup, ViewKeyCache};+use bevy::pbr::{self, DrawMesh, MeshInputUniform, MeshPipeline, MeshPipelineKey, MeshPipelineViewLayoutKey, MeshUniform, RenderMeshInstances, SetMeshBindGroup, SetMeshViewBindGroup, SetMeshViewEmptyBindGroup, ViewKeyCache};use bevy::platform::collections::HashSet;use bevy::prelude::*;use bevy::render::batching::gpu_preprocessing::{batch_and_prepare_sorted_render_phase, BatchedInstanceBuffers, IndirectParametersMetadata, UntypedPhaseIndirectParametersBuffers};@@ -31,7 +31,7 @@ use bevy::render::render_resource::*;use bevy::render::renderer::{RenderContext, ViewQuery};use bevy::render::sync_world::{MainEntity, MainEntityHashSet};use bevy::render::view::{ExtractedView, RenderVisibleEntities, RetainedViewEntity, ViewTarget};-use bevy::render::{Extract, Render, RenderApp, RenderDebugFlags, RenderStartup, RenderSystems};+use bevy::render::{Extract, Render, RenderApp, RenderDebugFlags, RenderSystems};use indexmap::IndexMap;use nonmax::NonMaxU32;@@ -61,7 +61,6 @@ pub fn install(app: &mut App) {.add_render_command::<Pass3d, DrawPass>().init_resource::<ViewSortedRenderPhases<Pass3d>>().init_resource::<Pending>()- .add_systems(RenderStartup, init.after(MeshPipelineSystems)).add_systems(ExtractSchedule, extract_phases).add_systems(Render, (queue.in_set(RenderSystems::QueueMeshes), sort_phase_system::<Pass3d>.in_set(RenderSystems::PhaseSort), batch_and_prepare_sorted_render_phase::<Pass3d, PassPipeline>.in_set(RenderSystems::PrepareResources))).add_systems(Core3d, draw.after(main_opaque_pass_3d).in_set(Core3dSystems::MainPass));@@ -69,11 +68,7 @@ pub fn install(app: &mut App) {#[derive(Resource)]pub struct PassPipeline {- mesh: MeshPipeline,-}--fn init(mut commands: Commands, mesh: Res<MeshPipeline>) {- commands.insert_resource(PassPipeline { mesh: mesh.clone() });+ pub(crate) mesh: MeshPipeline,}/// A pass pipeline's variant: the view and mesh's key, its shader and entry points.