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.

Mesh shaders: <MeshShaderPass> on a camera, and Bevy parity for shader_advanced/mesh_shader_intro, exact

shinyobjectzc240b8e99d85
diff --git a/bench/bevy-parity/examples.list b/bench/bevy-parity/examples.list
index 099f2a4c..099ea0c8 100644
--- a/bench/bevy-parity/examples.list
+++ b/bench/bevy-parity/examples.list
@@ -147,3 +147,4 @@ shader_advanced/custom_render_phase
shader_advanced/custom_shader_instancing
shader_advanced/deferred_raymarch
shader_advanced/manual_material
+shader_advanced/mesh_shader_intro
diff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsv
index ebd66400..164ac157 100644
--- a/bench/bevy-parity/runs.tsv
+++ b/bench/bevy-parity/runs.tsv
@@ -146,3 +146,4 @@ shader_advanced/custom_render_phase - 5,10
shader_advanced/custom_shader_instancing - 5,10
shader_advanced/deferred_raymarch - 5,10,30
shader_advanced/manual_material - 5,10,30
+shader_advanced/mesh_shader_intro - 5,10,30,60,120,240,300
diff --git a/docs/bevy-parity.md b/docs/bevy-parity.md
index 897d085b..b39d9d3d 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 **147**, passing **147**, excluded **17** (docs/bevy-parity/excluded.tsv), left **274**.
+Examples: **438**, ported **148**, passing **148**, excluded **17** (docs/bevy-parity/excluded.tsv), left **273**.
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.
@@ -242,6 +242,13 @@ doesn't pay.
| shader_advanced/manual_material | 10 | 1.000000 | 0 | 0 / 0 | 448 / 526 | 6 / 8 | 1 / 2 | 2.824 / 2.925 = 2.925 + 0 | yes | |
| shader_advanced/manual_material | 30 | 1.000000 | 0 | 0 / 0 | 448 / 526 | 6 / 8 | 1 / 2 | 2.425 / 1.489 = 1.489 + 0 | yes | |
| shader_advanced/manual_material | 5 | 1.000000 | 0 | 0 / 0 | 448 / 526 | 6 / 8 | 1 / 2 | 39.949 / 3.358 = 3.358 + 0 | yes | |
+| shader_advanced/mesh_shader_intro | 10 | 1.000000 | 0 | 1 / 1 | 442 / 527 | 6 / 8 | 2 / 2 | 2.768 / 1.964 = 1.964 + 0 | yes | |
+| shader_advanced/mesh_shader_intro | 120 | 1.000000 | 0 | 1 / 1 | 442 / 527 | 6 / 8 | 2 / 2 | 2.292 / 1.347 = 1.347 + 0 | yes | |
+| shader_advanced/mesh_shader_intro | 240 | 1.000000 | 0 | 1 / 1 | 442 / 527 | 6 / 8 | 2 / 2 | 2.208 / 1.355 = 1.355 + 0 | yes | |
+| shader_advanced/mesh_shader_intro | 30 | 1.000000 | 0 | 1 / 1 | 442 / 527 | 6 / 8 | 2 / 2 | 2.304 / 2.083 = 2.083 + 0 | yes | |
+| shader_advanced/mesh_shader_intro | 300 | 1.000000 | 0 | 1 / 1 | 442 / 527 | 6 / 8 | 2 / 2 | 2.146 / 1.378 = 1.378 + 0 | yes | |
+| shader_advanced/mesh_shader_intro | 5 | 1.000000 | 0 | 1 / 1 | 442 / 527 | 6 / 8 | 2 / 2 | 56.432 / 3.063 = 3.063 + 0 | yes | |
+| shader_advanced/mesh_shader_intro | 60 | 1.000000 | 0 | 1 / 1 | 442 / 527 | 6 / 8 | 2 / 2 | 2.447 / 1.525 = 1.525 + 0 | yes | |
## Excluded
diff --git a/docs/bevy-parity/results.jsonl b/docs/bevy-parity/results.jsonl
index 23ce5ea2..ac6d5207 100644
--- a/docs/bevy-parity/results.jsonl
+++ b/docs/bevy-parity/results.jsonl
@@ -229,3 +229,10 @@
{"example":"shader_advanced/manual_material","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["1.0000 1.0000 1.0000"],"frame":10,"frame_ms":2.824,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":18,"entities":526,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["1.0000 1.0000 1.0000"],"frame_ms":2.925,"step_ms":null,"cost_ms":2.925},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"shader_advanced/manual_material","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["1.0000 1.0000 1.0000"],"frame":30,"frame_ms":2.425,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":38,"entities":526,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["1.0000 1.0000 1.0000"],"frame_ms":1.489,"step_ms":null,"cost_ms":1.489},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"shader_advanced/manual_material","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":448,"extents":["1.0000 1.0000 1.0000"],"frame":5,"frame_ms":39.949,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":13,"entities":526,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["1.0000 1.0000 1.0000"],"frame_ms":3.358,"step_ms":null,"cost_ms":3.358},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader_advanced/mesh_shader_intro","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":1,"entities":442,"extents":["0.2500 0.2500 0.2500"],"frame":10,"frame_ms":2.768,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":17,"entities":527,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.2500 0.2500 0.2500"],"frame_ms":1.964,"step_ms":null,"cost_ms":1.964},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader_advanced/mesh_shader_intro","frame":120,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":1,"entities":442,"extents":["0.2500 0.2500 0.2500"],"frame":120,"frame_ms":2.292,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":127,"entities":527,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.2500 0.2500 0.2500"],"frame_ms":1.347,"step_ms":null,"cost_ms":1.347},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader_advanced/mesh_shader_intro","frame":240,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":1,"entities":442,"extents":["0.2500 0.2500 0.2500"],"frame":240,"frame_ms":2.208,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":247,"entities":527,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.2500 0.2500 0.2500"],"frame_ms":1.355,"step_ms":null,"cost_ms":1.355},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader_advanced/mesh_shader_intro","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":1,"entities":442,"extents":["0.2500 0.2500 0.2500"],"frame":30,"frame_ms":2.304,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":37,"entities":527,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.2500 0.2500 0.2500"],"frame_ms":2.083,"step_ms":null,"cost_ms":2.083},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader_advanced/mesh_shader_intro","frame":300,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":1,"entities":442,"extents":["0.2500 0.2500 0.2500"],"frame":300,"frame_ms":2.146,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":307,"entities":527,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.2500 0.2500 0.2500"],"frame_ms":1.378,"step_ms":null,"cost_ms":1.378},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader_advanced/mesh_shader_intro","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":1,"entities":442,"extents":["0.2500 0.2500 0.2500"],"frame":5,"frame_ms":56.432,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":12,"entities":527,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.2500 0.2500 0.2500"],"frame_ms":3.063,"step_ms":null,"cost_ms":3.063},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"shader_advanced/mesh_shader_intro","frame":60,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":1,"entities":442,"extents":["0.2500 0.2500 0.2500"],"frame":60,"frame_ms":2.447,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":67,"entities":527,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["0.2500 0.2500 0.2500"],"frame_ms":1.525,"step_ms":null,"cost_ms":1.525},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
diff --git a/sdk/raea/bench/bevy-parity/shader_advanced/mesh_shader_intro.tsx b/sdk/raea/bench/bevy-parity/shader_advanced/mesh_shader_intro.tsx
new file mode 100644
index 00000000..70fe80f4
--- /dev/null
+++ b/sdk/raea/bench/bevy-parity/shader_advanced/mesh_shader_intro.tsx
@@ -0,0 +1,34 @@
+// Bevy v0.20.0 examples/shader_advanced/mesh_shader_intro.rs in raea's TSX (docs/control.feature FC2d): a mesh-shader
+// pipeline drawn after the main opaque pass, a <MeshShaderPass> on the camera with assets/shaders/mesh_shader_intro's
+// task.wesl, mesh.wesl and fragment.wesl as written (each importing bindings.wesl beside it), dispatched as one
+// workgroup: the task shader asks for u32(globals.time) workgroups on each axis, and each makes a cube of 0.1 m half
+// size at its id, coloured by its id over their count and culled where sin(time * 10 + x + y + z) > 0.8. A 0.5 m cube of
+// srgb(124, 144, 255) at (0, 0.5, 0), a shadow-casting PointLight at (4, 8, 4), and the camera at (-9, 1, -9) looking
+// at (9, 4, 9) with Msaa off, in Bevy's default 1280 x 720 window. The example needs a GPU with mesh shaders.
+import { Composition, registerRoot, staticFile } from "raea";
+import { BevyComponent, MeshShaderPass } from "raea/3d";
+import { Camera3d } from "raea/camera";
+import { PointLight } from "raea/light";
+import { Cuboid, Mesh3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { Transform } from "raea/transform";
+
+const DIR = "shaders/mesh_shader_intro";
+
+function Shot() {
+ return (
+ <>
+ <Mesh3d transform={Transform.fromXyz(0, 0.5, 0)}>
+ <Cuboid half_size={[0.25, 0.25, 0.25]} />
+ <StandardMaterial base_color="rgb(124, 144, 255)" />
+ </Mesh3d>
+ <PointLight shadow_maps_enabled transform={Transform.fromXyz(4, 8, 4)} />
+ <Camera3d transform={Transform.fromXyz(-9, 1, -9).lookingAt([9, 4, 9])}>
+ <BevyComponent type="bevy_render::view::Msaa" value="Off" />
+ <MeshShaderPass task={staticFile(`${DIR}/task.wesl`)} mesh={staticFile(`${DIR}/mesh.wesl`)} fragment={staticFile(`${DIR}/fragment.wesl`)} />
+ </Camera3d>
+ </>
+ );
+}
+
+registerRoot(() => <Composition id="main" component={Shot} durationInFrames={301} fps={60} width={1280} height={720} />);
diff --git a/sdk/render/src/3d.tsx b/sdk/render/src/3d.tsx
index 5dc4d675..be5d883e 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, ShaderInstances, GBufferPass, 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, GBufferPassProps, 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, GBufferPass, MeshShaderPass, 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, GBufferPassProps, MeshShaderPassProps, 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.tsx
index 18a12e95..d2202302 100644
--- a/sdk/render/src/3d/phase.tsx
+++ b/sdk/render/src/3d/phase.tsx
@@ -110,3 +110,29 @@ export function GBufferPass(p: GBufferPassProps) {
if (typeof shader !== "string" || !shader) throw new TypeError(`GBufferPass: shader is a shader file, staticFile("shaders/x.wesl"), got ${JSON.stringify(shader)}`);
return <BevyComponent type="raea_sys_phase::GBufferPass" value={{ shader: assetPath(shader), fragment, shadow }} />;
}
+
+export interface MeshShaderPassProps {
+ /** the task (amplification) shader file, compiled as written; none when left out, and the draw's workgroups are the
+ * mesh shader's */
+ task?: string;
+ /** the mesh shader file, compiled as written: it makes the primitives the fragment shader draws */
+ mesh: string;
+ /** the fragment shader file, compiled as written. Each file has the one entry point of its stage; bind group 0 is
+ * Globals (binding 0) and the view uniform (binding 1) in all three, and a file's `import super::NAME` reads
+ * NAME.wesl beside it */
+ fragment: string;
+ /** the draw's workgroup count, [x, y, z] (draw_mesh_tasks); [1, 1, 1] when left out */
+ groups?: [number, number, number];
+}
+
+/** Inside a Camera3d: your task and mesh shaders make primitives on the GPU and your fragment shader draws them into
+ * the view's colour and depth (compared GreaterEqual) after the main opaque pass (Bevy's
+ * shader_advanced/mesh_shader_intro). It needs a GPU with mesh shaders, as Apple silicon's Metal has; elsewhere it
+ * draws nothing and says so.
+ * @bevy raea_sys_phase::MeshShaderPass */
+export function MeshShaderPass(p: MeshShaderPassProps) {
+ const { task, mesh, fragment, groups = [1, 1, 1] } = p;
+ for (const [k, f] of [["mesh", mesh], ["fragment", fragment], ...(task !== undefined ? [["task", task]] : [])] as const) if (typeof f !== "string" || !f) throw new TypeError(`MeshShaderPass: ${k} is a shader file, staticFile("shaders/x.wesl"), got ${JSON.stringify(f)}`);
+ if (!Array.isArray(groups) || groups.length !== 3 || !groups.every((n) => Number.isInteger(n) && n >= 0)) throw new TypeError(`MeshShaderPass: groups is [x, y, z] whole numbers, got ${JSON.stringify(groups)}`);
+ return <BevyComponent type="raea_sys_phase::MeshShaderPass" value={{ task: task === undefined ? "" : assetPath(task), mesh: assetPath(mesh), fragment: assetPath(fragment), groups }} />;
+}
diff --git a/systems/phase/src/lib.rs b/systems/phase/src/lib.rs
index ffb5dc95..6d908f0f 100644
--- a/systems/phase/src/lib.rs
+++ b/systems/phase/src/lib.rs
@@ -6,7 +6,8 @@
//! 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). A camera's GBufferPass draws a fullscreen shader into the
-//! deferred G-buffer and the shadow maps (shader_advanced/deferred_raymarch, gbuffer.rs).
+//! deferred G-buffer and the shadow maps (shader_advanced/deferred_raymarch, gbuffer.rs), and its MeshShaderPass draws by task and mesh shaders
+//! (shader_advanced/mesh_shader_intro, mesh_shader.rs).
use bevy::camera::visibility::{self, VisibilityClass};
use bevy::prelude::*;
@@ -17,10 +18,12 @@ mod draw;
mod gbuffer;
mod instances;
mod mesh_pass;
+mod mesh_shader;
pub use gbuffer::GBufferPass;
pub use instances::ShaderInstances;
pub use mesh_pass::MeshPass;
+pub use mesh_shader::MeshShaderPass;
/// A vertex attribute: its format (Bevy's VertexFormat by name, "Float32x3"), byte offset and shader location.
#[derive(Clone, Debug, Default, Reflect)]
@@ -90,9 +93,8 @@ pub(crate) fn register<C: Shaded>(world: &mut World) {
}
}
for (e, path) in todo {
- match std::fs::read_to_string(&path) {
- Ok(src) => {
- let id = raea_sys_shader::register(world, src, &[], C::NAME, "raea_sys_phase");
+ match file(world, &path, C::NAME) {
+ Ok(id) => {
if let Some(mut c) = world.get_mut::<C>(e) {
c.keep((path, id));
}
@@ -102,6 +104,14 @@ pub(crate) fn register<C: Shaded>(world: &mut World) {
}
}
+/// A shader file read and registered as written, in an embedded folder of its own with each module it imports by
+/// `super::NAME` from beside it (raea-sys-shader's folder): the id its module has.
+pub(crate) fn file(world: &mut World, path: &str, kind: &str) -> Result<u128, String> {
+ let src = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
+ let krate = raea_sys_shader::own::folder(world, path, &src)?;
+ Ok(raea_sys_shader::register(world, src, &[], kind, &krate))
+}
+
/// 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() });
@@ -116,6 +126,7 @@ pub fn install(app: &mut App) {
mesh_pass::install(app);
instances::install(app);
gbuffer::install(app);
+ mesh_shader::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_shader.rs b/systems/phase/src/mesh_shader.rs
new file mode 100644
index 00000000..faabc1b2
--- /dev/null
+++ b/systems/phase/src/mesh_shader.rs
@@ -0,0 +1,145 @@
+//! A camera's mesh-shader draw (docs/control.feature FC2d), as Bevy's shader_advanced/mesh_shader_intro draws its
+//! cubes: a camera with a MeshShaderPass runs your task shader (when it has one) and mesh shader, which make their
+//! primitives on the GPU and hand them to your fragment shader, straight into the view's colour and depth (compared
+//! GreaterEqual, written) after the main opaque pass. Each is a shader file compiled as written, with the one entry point
+//! of its stage, and `groups` is the draw's workgroup count (draw_mesh_tasks: the task shader's, or the mesh shader's
+//! with no task shader). Bind group 0 is Globals (binding 0) and the view uniform (binding 1, dynamic), in every stage.
+//! It needs a GPU with mesh shaders (wgpu's EXPERIMENTAL_MESH_SHADER, which raea's device takes where the adapter has
+//! it); without them the pass is logged and draws nothing.
+
+use std::collections::HashMap;
+
+use bevy::camera::{MainPassResolutionOverride, Viewport};
+use bevy::core_pipeline::core_3d::{main_opaque_pass_3d, CORE_3D_DEPTH_FORMAT};
+use bevy::core_pipeline::{Core3d, Core3dSystems};
+use bevy::material::descriptor::{MeshPipelineDescriptor, MeshState, TaskState};
+use bevy::prelude::*;
+use bevy::render::camera::ExtractedCamera;
+use bevy::render::extract_component::{ExtractComponent, ExtractComponentPlugin};
+use bevy::render::globals::{GlobalsBuffer, GlobalsUniform};
+use bevy::render::render_resource::binding_types::uniform_buffer;
+use bevy::render::render_resource::*;
+use bevy::render::renderer::{RenderContext, RenderDevice, ViewQuery};
+use bevy::render::settings::WgpuFeatures;
+use bevy::render::view::{ViewDepthStencilTexture, ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms};
+use bevy::render::{Render, RenderApp, RenderStartup, RenderSystems};
+
+/// A camera's mesh-shader draw: its task shader file ("" for none), mesh and fragment shader files, and its workgroup
+/// count.
+#[derive(Component, Clone, Debug, Default, Reflect, ExtractComponent)]
+#[extract_app(RenderApp)]
+#[reflect(Component, Default)]
+#[type_path = "raea_sys_phase"]
+pub struct MeshShaderPass {
+ pub task: String,
+ pub mesh: String,
+ pub fragment: String,
+ pub groups: [u32; 3],
+ /// its files, registered as written (raea-sys-shader), and the ids register gave them (0 for no task shader)
+ #[reflect(ignore)]
+ pub registered: Option<([String; 3], [u128; 3])>,
+}
+
+impl MeshShaderPass {
+ fn files(&self) -> [String; 3] {
+ [self.task.clone(), self.mesh.clone(), self.fragment.clone()]
+ }
+}
+
+pub fn install(app: &mut App) {
+ app.register_type::<MeshShaderPass>();
+ app.add_systems(PostUpdate, register);
+ app.add_plugins(ExtractComponentPlugin::<MeshShaderPass>::default());
+ let Some(r) = app.get_sub_app_mut(RenderApp) else { return };
+ r.add_systems(RenderStartup, init)
+ .add_systems(Render, queue.in_set(RenderSystems::Queue))
+ .add_systems(Core3d, draw.after(main_opaque_pass_3d).in_set(Core3dSystems::MainPass));
+}
+
+/// Each new or changed pass's files read and registered as written (a file it can't read is logged).
+fn register(world: &mut World) {
+ let mut q = world.query_filtered::<(Entity, &MeshShaderPass), Changed<MeshShaderPass>>();
+ let todo: Vec<_> = q.iter(world).filter(|(_, p)| p.registered.as_ref().map(|r| &r.0) != Some(&p.files())).map(|(e, p)| (e, p.files())).collect();
+ 'pass: for (e, files) in todo {
+ let mut ids = [0; 3];
+ for (i, f) in files.iter().enumerate().filter(|(i, f)| *i > 0 || !f.is_empty()) {
+ match crate::file(world, f, "MeshShaderPass") {
+ Ok(id) => ids[i] = id,
+ Err(err) => {
+ error!("MeshShaderPass: its shader {f}: {err}");
+ continue 'pass;
+ }
+ }
+ }
+ if let Some(mut p) = world.get_mut::<MeshShaderPass>(e) {
+ p.registered = Some((files, ids));
+ }
+ }
+}
+
+/// The passes' bind group layout, and each pass's pipeline by its shaders and the view's target.
+#[derive(Resource)]
+struct Pipelines {
+ layout: BindGroupLayoutDescriptor,
+ made: HashMap<([u128; 3], TextureFormat, u32), CachedRenderPipelineId>,
+}
+
+fn init(mut commands: Commands) {
+ let stages = ShaderStages::TASK | ShaderStages::MESH | ShaderStages::FRAGMENT;
+ let layout = BindGroupLayoutDescriptor::new("raea_mesh_shader_pass", &BindGroupLayoutEntries::sequential(stages, (uniform_buffer::<GlobalsUniform>(false), uniform_buffer::<ViewUniform>(true))));
+ commands.insert_resource(Pipelines { layout, made: HashMap::new() });
+}
+
+/// The key a view's pipeline is kept by: its shaders, its target's format and its sample count.
+fn key(p: &MeshShaderPass, target: &ViewTarget, msaa: &Msaa) -> Option<([u128; 3], TextureFormat, u32)> {
+ Some((p.registered.as_ref()?.1, target.main_texture_format(), msaa.samples()))
+}
+
+/// Each view's pipeline queued once its shaders are registered, where the device has mesh shaders.
+fn queue(cache: Res<PipelineCache>, device: Res<RenderDevice>, mut pipes: ResMut<Pipelines>, views: Query<(&MeshShaderPass, &ViewTarget, &Msaa)>, mut told: Local<bool>) {
+ for (p, target, msaa) in &views {
+ let Some(k) = key(p, target, msaa) else { continue };
+ if pipes.made.contains_key(&k) {
+ continue;
+ }
+ if !device.features().contains(WgpuFeatures::EXPERIMENTAL_MESH_SHADER) {
+ if !std::mem::replace(&mut *told, true) {
+ error!("MeshShaderPass: this GPU has no mesh shaders (wgpu's EXPERIMENTAL_MESH_SHADER), so it draws nothing");
+ }
+ return;
+ }
+ let uuids = k.0.map(bevy::asset::uuid::Uuid::from_u128);
+ let shader = |stage: usize| Handle::<Shader>::Uuid(uuids[stage], core::marker::PhantomData);
+ let depth = DepthStencilState { format: CORE_3D_DEPTH_FORMAT, depth_write_enabled: Some(true), depth_compare: Some(CompareFunction::GreaterEqual), stencil: default(), bias: default() };
+ let id = cache.queue_mesh_pipeline(MeshPipelineDescriptor {
+ label: Some("raea_mesh_shader_pass".into()),
+ layout: vec![pipes.layout.clone()],
+ immediate_size: 0,
+ task: (k.0[0] != 0).then(|| TaskState { shader: shader(0), ..default() }),
+ mesh: MeshState { shader: shader(1), ..default() },
+ primitive: default(),
+ depth_stencil: Some(depth),
+ multisample: MultisampleState { count: k.2, ..default() },
+ fragment: Some(FragmentState { shader: shader(2), targets: vec![Some(ColorTargetState { format: k.1, blend: None, write_mask: ColorWrites::ALL })], ..default() }),
+ zero_initialize_workgroup_memory: false,
+ });
+ pipes.made.insert(k, id);
+ }
+}
+
+/// The draw into the view's colour and depth, in the camera's viewport.
+#[allow(clippy::too_many_arguments)]
+fn draw(view: ViewQuery<(&ExtractedCamera, Option<&MainPassResolutionOverride>, &ViewTarget, &Msaa, &ViewDepthStencilTexture, &ViewUniformOffset, &MeshShaderPass)>, pipes: Res<Pipelines>, cache: Res<PipelineCache>, views: Res<ViewUniforms>, globals: Res<GlobalsBuffer>, mut ctx: RenderContext) {
+ let (camera, over, target, msaa, depth, offset, p) = view.into_inner();
+ let Some(pipeline) = key(p, target, msaa).and_then(|k| pipes.made.get(&k)).and_then(|id| cache.get_render_pipeline(*id)) else { return };
+ let (Some(g), Some(v)) = (globals.buffer.binding(), views.uniforms.binding()) else { return };
+ let group = ctx.render_device().create_bind_group("raea_mesh_shader_pass", &cache.get_bind_group_layout(&pipes.layout), &BindGroupEntries::sequential((g, v)));
+ let mut pass = ctx.begin_tracked_render_pass(RenderPassDescriptor { label: Some("raea_mesh_shader_pass"), color_attachments: &[Some(target.get_color_attachment())], depth_stencil_attachment: Some(depth.get_attachment(StoreOp::Store)), timestamp_writes: None, occlusion_query_set: None, multiview_mask: None });
+ pass.set_render_pipeline(pipeline);
+ pass.set_bind_group(0, &group, &[offset.offset]);
+ if let Some(v) = Viewport::from_viewport_and_override(camera.viewport.as_ref(), over) {
+ pass.set_camera_viewport(&v);
+ }
+ let [x, y, z] = p.groups;
+ pass.draw_mesh_tasks(x, y, z);
+}
diff --git a/systems/shader/src/own.rs b/systems/shader/src/own.rs
index b90da70d..ac825455 100644
--- a/systems/shader/src/own.rs
+++ b/systems/shader/src/own.rs
@@ -374,7 +374,7 @@ pub fn picture(world: &mut World, path: &str) -> Result<Handle<Image>, String> {
/// The embedded folder a file's module goes in (raea_sys_shader/d{hash of its folder}), with every module it imports
/// by `super::NAME` registered there from its own folder, and theirs in turn.
-fn folder(world: &mut World, path: &str, src: &str) -> Result<String, String> {
+pub fn folder(world: &mut World, path: &str, src: &str) -> Result<String, String> {
let dir = std::path::Path::new(path).parent().unwrap_or(std::path::Path::new("."));
let mut h = std::collections::hash_map::DefaultHasher::new();
dir.hash(&mut h);
@@ -398,19 +398,26 @@ fn folder(world: &mut World, path: &str, src: &str) -> Result<String, String> {
Ok(krate)
}
-/// The modules a source imports from its own folder: each `super::NAME` of its `import` statements.
+/// The modules a source imports from its own folder: each `super::NAME` of its `import` statements, a statement read
+/// to its `;` over lines (`import super::{\n bindings::{a, B},\n};`, as Bevy's mesh_shader_intro writes one).
fn siblings(src: &str) -> Vec<String> {
let mut out = Vec::new();
- for line in src.lines().map(str::trim).filter(|l| l.starts_with("import ")) {
- for (i, _) in line.match_indices("super::") {
- // super::NAME::item, or super::{NAME::item, OTHER::item}
- let after = &line[i + 7..];
- let parts: Vec<&str> = match after.strip_prefix('{') {
- Some(r) => r.split('}').next().unwrap_or("").split(',').collect(),
- None => vec![after],
- };
- for p in parts {
- let name: String = p.trim().chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
+ let stmts = src.split(';').filter_map(|s| s.lines().position(|l| l.trim_start().starts_with("import ")).map(|i| s.lines().skip(i).collect::<Vec<_>>().join(" ")));
+ for stmt in stmts {
+ for (i, _) in stmt.match_indices("super::") {
+ // super::NAME::item, or super::{NAME::item, OTHER::{a, b}}: each top-level item's first name
+ let (mut depth, mut items, after) = (0, vec![String::new()], &stmt[i + 7..]);
+ for c in after.strip_prefix('{').unwrap_or(after).chars() {
+ match c {
+ '}' if depth == 0 => break,
+ ',' if depth == 0 => items.push(String::new()),
+ c => {
+ depth += (c == '{') as i32 - (c == '}') as i32;
+ items.last_mut().unwrap().push(c);
+ }
+ }
+ }
+ for name in items.iter().map(|p| p.trim().chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect::<String>()) {
if !name.is_empty() && !out.contains(&name) {
out.push(name);
}
@@ -451,6 +458,7 @@ mod tests {
fn a_files_own_folder_imports_are_found() {
let src = "import bevy_pbr::forward_io::VertexOutput;\nimport super::custom_material_import::COLOR_MULTIPLIER;\nimport super::{a::X, b_2::Y};\nfn f() { super::not_an_import(); }\n";
assert_eq!(super::siblings(src), vec!["custom_material_import".to_string(), "a".into(), "b_2".into()]);
+ assert_eq!(super::siblings("import super::{\n bindings::{globals, TaskPayload},\n};\nenable x;"), vec!["bindings".to_string()]);
assert!(super::alpha_mode(Some(&serde_json::json!("Blend"))).unwrap() == Some(bevy::prelude::AlphaMode::Blend));
assert!(super::alpha_mode(Some(&serde_json::json!({"Mask": 0.5}))).unwrap() == Some(bevy::prelude::AlphaMode::Mask(0.5)));
assert!(super::alpha_mode(Some(&serde_json::json!("Clear"))).is_err());