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
A camera's depth as a texture: <DepthCopy>, depth images and depth textures in <Material>; Bevy parity for shader_advanced/render_depth_to_texture
shinyobjectz426567fb6332
diff --git a/bench/bevy-parity/examples.list b/bench/bevy-parity/examples.listindex 099ea0c8..04fdb0fa 100644--- a/bench/bevy-parity/examples.list+++ b/bench/bevy-parity/examples.list@@ -148,3 +148,4 @@ shader_advanced/custom_shader_instancingshader_advanced/deferred_raymarchshader_advanced/manual_materialshader_advanced/mesh_shader_intro+shader_advanced/render_depth_to_texturediff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsvindex 164ac157..c1c05deb 100644--- a/bench/bevy-parity/runs.tsv+++ b/bench/bevy-parity/runs.tsv@@ -147,3 +147,4 @@ shader_advanced/custom_shader_instancing - 5,10shader_advanced/deferred_raymarch - 5,10,30shader_advanced/manual_material - 5,10,30shader_advanced/mesh_shader_intro - 5,10,30,60,120,240,300+shader_advanced/render_depth_to_texture - 5,10,30,60diff --git a/docs/bevy-parity.md b/docs/bevy-parity.mdindex b39d9d3d..6364bec9 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 **148**, passing **148**, excluded **17** (docs/bevy-parity/excluded.tsv), left **273**.+Examples: **438**, ported **149**, passing **149**, excluded **17** (docs/bevy-parity/excluded.tsv), left **272**.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.@@ -249,6 +249,10 @@ doesn't pay.| 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 | |+| shader_advanced/render_depth_to_texture | 10 | 0.999617 | 6 | 1 / 1 | 452 / 536 | 7 / 9 | 2 / 3 | 2.511 / 1.737 = 1.737 + 0 | yes | |+| shader_advanced/render_depth_to_texture | 30 | 0.999617 | 6 | 1 / 1 | 452 / 536 | 7 / 9 | 2 / 3 | 2.149 / 1.113 = 1.113 + 0 | yes | |+| shader_advanced/render_depth_to_texture | 5 | 0.999617 | 6 | 1 / 1 | 452 / 536 | 7 / 9 | 2 / 3 | 47.576 / 2.77 = 2.77 + 0 | yes | |+| shader_advanced/render_depth_to_texture | 60 | 0.999617 | 6 | 1 / 1 | 452 / 536 | 7 / 9 | 2 / 3 | 1.975 / 0.999 = 0.999 + 0 | yes | |## Excludeddiff --git a/docs/bevy-parity/results.jsonl b/docs/bevy-parity/results.jsonlindex ac6d5207..89a8d7db 100644--- a/docs/bevy-parity/results.jsonl+++ b/docs/bevy-parity/results.jsonl@@ -236,3 +236,7 @@{"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":""}+{"example":"shader_advanced/render_depth_to_texture","frame":10,"ssim":0.999617,"tile":6,"bevy":{"batch_keys":1,"entities":452,"extents":["1.5000 1.5000 1.5000","2.0000 2.0000 0.0000"],"frame":10,"frame_ms":2.511,"materials":2,"mesh_entities":2,"meshes":7,"other_material":1,"visible":2},"raea":{"frame":17,"entities":536,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":1,"other_material":1,"extents":["1.5000 1.5000 1.5000","2.0000 2.0000 0.0000"],"frame_ms":1.737,"step_ms":null,"cost_ms":1.737},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/render_depth_to_texture","frame":30,"ssim":0.999617,"tile":6,"bevy":{"batch_keys":1,"entities":452,"extents":["1.5000 1.5000 1.5000","2.0000 2.0000 0.0000"],"frame":30,"frame_ms":2.149,"materials":2,"mesh_entities":2,"meshes":7,"other_material":1,"visible":2},"raea":{"frame":37,"entities":536,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":1,"other_material":1,"extents":["1.5000 1.5000 1.5000","2.0000 2.0000 0.0000"],"frame_ms":1.113,"step_ms":null,"cost_ms":1.113},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/render_depth_to_texture","frame":5,"ssim":0.999617,"tile":6,"bevy":{"batch_keys":1,"entities":452,"extents":["1.5000 1.5000 1.5000","2.0000 2.0000 0.0000"],"frame":5,"frame_ms":47.576,"materials":2,"mesh_entities":2,"meshes":7,"other_material":1,"visible":2},"raea":{"frame":12,"entities":536,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":1,"other_material":1,"extents":["1.5000 1.5000 1.5000","2.0000 2.0000 0.0000"],"frame_ms":2.77,"step_ms":null,"cost_ms":2.77},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/render_depth_to_texture","frame":60,"ssim":0.999617,"tile":6,"bevy":{"batch_keys":1,"entities":452,"extents":["1.5000 1.5000 1.5000","2.0000 2.0000 0.0000"],"frame":60,"frame_ms":1.975,"materials":2,"mesh_entities":2,"meshes":7,"other_material":1,"visible":2},"raea":{"frame":67,"entities":536,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":1,"other_material":1,"extents":["1.5000 1.5000 1.5000","2.0000 2.0000 0.0000"],"frame_ms":0.999,"step_ms":null,"cost_ms":0.999},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}diff --git a/runtime/plugins/src/fields.rs b/runtime/plugins/src/fields.rsindex a16a20d7..2c47cf20 100644--- a/runtime/plugins/src/fields.rs+++ b/runtime/plugins/src/fields.rs@@ -190,8 +190,11 @@ impl Fields<'_> {// a named image a camera draws into ("render:mirror" or "render:mirror:256x256", 512 x 512 if not// given): every field naming it gets the same image, so a camera's RenderTarget and a material's texture// meet in it+ // ("render:NAME:WxH:depth" a depth image, Depth32Float with a comparison sampler, a camera's DepthCopy+ // copies its depth into and a Material samples as texture_depth_2d)Value::String(x) if asset == TypeId::of::<Image>() && x.starts_with("render:") => {let rest = &x["render:".len()..];+ let (rest, depth) = rest.strip_suffix(":depth").map_or((rest, false), |r| (r, true));let (name, size) = match rest.rsplit_once(':') {Some((n, sz)) if sz.contains('x') => (n, Some(sz)),_ => (rest, None),@@ -213,7 +216,7 @@ impl Fields<'_> {}return Ok(hd.0.clone().untyped());}- let img = Image::new_target_texture(w, h, bevy::render::render_resource::TextureFormat::Rgba8UnormSrgb, None);+ let img = if depth { raea_sys_shader::own::depth_image(w, h) } else { Image::new_target_texture(w, h, bevy::render::render_resource::TextureFormat::Rgba8UnormSrgb, None) };let hd = self.world.resource_mut::<Assets<Image>>().add(img);self.world.get_resource_or_init::<RenderImages>().0.insert(name.to_string(), (hd.clone(), (w, h)));Ok(hd.untyped())diff --git a/sdk/raea/bench/bevy-parity/shader_advanced/render_depth_to_texture.tsx b/sdk/raea/bench/bevy-parity/shader_advanced/render_depth_to_texture.tsxnew file mode 100644index 00000000..508f9847--- /dev/null+++ b/sdk/raea/bench/bevy-parity/shader_advanced/render_depth_to_texture.tsx@@ -0,0 +1,80 @@+// Bevy v0.20.0 examples/shader_advanced/render_depth_to_texture.rs in raea's TSX (docs/control.feature FC2d): a+// depth-only camera (order -1, RenderTarget::None of 256 x 256, Msaa off, DepthPrepass) at (-4, -5, 5) looking at the+// origin, its depth copied after its prepass into a 256 x 256 Depth32Float image (a <DepthCopy>), which a 4 m plane+// facing +Z at (10, 4, 0), scaled 2.5, shows through assets/shaders/show_depth_texture_material.wesl as written (its+// texture_depth_2d and sampler_comparison). A 3 m white cube at the origin turned each update by rotate_x(1.5 dt),+// rotate_y(1.1 dt) and rotate_z(-1.3 dt) (dt 1/60 s, none on the first update), Bevy's default PointLight at (5, 6, 7),+// the main camera at (5, 2, 30) looking at (5, 2, 0) with Msaa off, a LIME cone gizmo (radius 1, height 3, Bevy's+// default resolution of 5) at the depth camera turned a quarter about its X, and "Use WASD to move the secondary camera"+// 12 px from the top left, in Bevy's default 1280 x 720 window. The camera moves only under input.+import { Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { BevyComponent, DepthCopy, Gizmo } from "raea/3d";+import { Camera3d } from "raea/camera";+import { PointLight } from "raea/light";+import { Cuboid, Mesh3d, Plane3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Quat, Transform } from "raea/transform";+import { Text, px } from "raea/ui";+import { Material } from "@raea/render/bevy3d";++const f = Math.fround;+const DT = f(1 / 60);+const DEPTH = "render:depth:256x256:depth";+const LIME = "#00ff00";++/** glam's f32 Quat::from_rotation_{x,y,z} and Quat * Quat */+const axis = (i: number, a: number): Quat => {+ const h = f(a * 0.5);+ const q: Quat = [0, 0, 0, f(Math.cos(h))];+ q[i] = f(Math.sin(h));+ return q;+};+const mul = (a: Quat, b: Quat): Quat => Quat.mul(a, b).map(f) as Quat;++/** rotate_cube: each update after the first, rotate_x, rotate_y then rotate_z by its delta (each premultiplied) */+function cubeAt(frame: number): Quat {+ let q: Quat = [0, 0, 0, 1];+ for (let n = 0; n < frame; n++) for (const [i, w] of [[0, 1.5], [1, 1.1], [2, -1.3]] as const) q = mul(axis(i, f(w * DT)), q);+ return q;+}++/** Bevy's primitive_3d(&Cone { radius: 1, height: 3 }) at the depth camera: its base circle's 5 points closed, each+ * point but the first joined to the apex, then the circle's 5 sides */+function cone(): [[number, number, number], [number, number, number]][] {+ const cam = Transform.fromXyz(-4, -5, 5).lookingAt([0, 0, 0]);+ const rot = Quat.mul(cam.rotation, Quat.fromRotationX(Math.PI / 2));+ const at = (v: [number, number, number]) => Quat.mulVec3(rot, v).map((x, i) => x + cam.translation[i]) as [number, number, number];+ const apex = at([0, 1.5, 0]);+ const circle = [0, 1, 2, 3, 4, 5].map((p) => at([Math.sin((p * 2 * Math.PI) / 5), -1.5, Math.cos((p * 2 * Math.PI) / 5)]));+ return [...circle.slice(1).map((c) => [c, apex] as [typeof c, typeof c]), ...circle.slice(0, 5).map((c, i) => [c, circle[i + 1]] as [typeof c, typeof c])];+}++function Shot() {+ const frame = useCurrentFrame();+ return (+ <>+ <Mesh3d transform={{ translation: [0, 0, 0], rotation: cubeAt(frame) }}>+ <Cuboid half_size={[1.5, 1.5, 1.5]} />+ <StandardMaterial base_color="#ffffff" />+ </Mesh3d>+ <Mesh3d transform={Transform.fromXyz(10, 4, 0).withScale([2.5, 2.5, 2.5])}>+ <Plane3d normal={[0, 0, 1]} half_size={[2, 2]} />+ <Material fragment={staticFile("shaders/show_depth_texture_material.wesl")} textures={{ depth_texture: DEPTH }} />+ </Mesh3d>+ <PointLight transform={Transform.fromXyz(5, 6, 7)} />+ <Camera3d order={-1} transform={Transform.fromXyz(-4, -5, 5).lookingAt([0, 0, 0])}>+ <BevyComponent type="bevy_camera::camera::RenderTarget" value={{ None: { size: [256, 256] } }} />+ <BevyComponent type="bevy_render::view::Msaa" value="Off" />+ <BevyComponent type="bevy_core_pipeline::prepass::DepthPrepass" value={{}} />+ <DepthCopy image={DEPTH} />+ </Camera3d>+ <Camera3d transform={Transform.fromXyz(5, 2, 30).lookingAt([5, 2, 0])}>+ <BevyComponent type="bevy_render::view::Msaa" value="Off" />+ </Camera3d>+ <Gizmo lines={cone()} color={LIME} />+ <Text position_type="Absolute" top={px(12)} left={px(12)}>Use WASD to move the secondary camera</Text>+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/render/src/3d.tsx b/sdk/render/src/3d.tsxindex be5d883e..459f1404 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, 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 { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, SurfaceShader, ThreeShaderMaterial, surfaceShader, samplerSpec, FramePass, Compute, PhaseItem, MeshPass, ShaderInstances, GBufferPass, MeshShaderPass, DepthCopy, 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, DepthCopyProps, 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 d2202302..56f13991 100644--- a/sdk/render/src/3d/phase.tsx+++ b/sdk/render/src/3d/phase.tsx@@ -136,3 +136,18 @@ export function MeshShaderPass(p: MeshShaderPassProps) {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 }} />;}++export interface DepthCopyProps {+ /** the depth image, "render:NAME:WxH:depth": the camera's depth is copied into it, and a Material's texture of that+ * name is it (a texture_depth_2d with a sampler_comparison) */+ image: string;+}++/** Inside a Camera3d: its depth buffer copied each frame, after its prepass and before its main pass, into a depth+ * image a Material samples (Bevy's shader_advanced/render_depth_to_texture, whose depth-only camera has Bevy's+ * DepthPrepass, RenderTarget::None and Msaa off).+ * @bevy raea_sys_phase::DepthCopy */+export function DepthCopy({ image }: DepthCopyProps) {+ if (typeof image !== "string" || !/^render:[^:]+:\d+x\d+:depth$/.test(image)) throw new TypeError(`DepthCopy: image is a depth image, "render:NAME:WxH:depth", got ${JSON.stringify(image)}`);+ return <BevyComponent type="raea_sys_phase::DepthCopy" value={{ image }} />;+}diff --git a/systems/phase/src/depth_copy.rs b/systems/phase/src/depth_copy.rsnew file mode 100644index 00000000..e2d62b3c--- /dev/null+++ b/systems/phase/src/depth_copy.rs@@ -0,0 +1,41 @@+//! A camera's depth copied into an image (docs/control.feature FC2d), as Bevy's shader_advanced/render_depth_to_texture+//! copies its depth-only camera's: a camera with a DepthCopy has its depth buffer (ViewDepthStencilTexture) copied after+//! its prepass and before its main pass into `image`, a "render:NAME:WxH:depth" (raea-runtime-plugins' fields), which a+//! Material samples as a texture_depth_2d. The copy is the image's size from the depth buffer's corner; a depth buffer+//! smaller than the image isn't copied.++use bevy::core_pipeline::{Core3d, Core3dSystems};+use bevy::prelude::*;+use bevy::render::extract_component::{ExtractComponent, ExtractComponentPlugin};+use bevy::render::render_asset::RenderAssets;+use bevy::render::renderer::{RenderContext, ViewQuery};+use bevy::render::texture::GpuImage;+use bevy::render::view::ViewDepthStencilTexture;+use bevy::render::RenderApp;++/// The image a camera's depth is copied into each frame.+#[derive(Component, Clone, Debug, Default, Reflect, ExtractComponent)]+#[extract_app(RenderApp)]+#[reflect(Component, Default)]+#[type_path = "raea_sys_phase"]+pub struct DepthCopy {+ pub image: Handle<Image>,+}++pub fn install(app: &mut App) {+ app.register_type::<DepthCopy>();+ app.add_plugins(ExtractComponentPlugin::<DepthCopy>::default());+ let Some(r) = app.get_sub_app_mut(RenderApp) else { return };+ r.add_systems(Core3d, copy.after(Core3dSystems::Prepass).before(Core3dSystems::MainPass));+}++/// The view's depth into its DepthCopy's image.+fn copy(view: ViewQuery<(&ViewDepthStencilTexture, &DepthCopy)>, images: Res<RenderAssets<GpuImage>>, mut ctx: RenderContext) {+ let (depth, c) = view.into_inner();+ let Some(img) = images.get(&c.image) else { return };+ let (from, to) = (depth.texture().size(), img.texture.size());+ if from.width < to.width || from.height < to.height {+ return;+ }+ ctx.command_encoder().copy_texture_to_texture(depth.texture().as_image_copy(), img.texture.as_image_copy(), to);+}diff --git a/systems/phase/src/lib.rs b/systems/phase/src/lib.rsindex 6d908f0f..c4213075 100644--- a/systems/phase/src/lib.rs+++ b/systems/phase/src/lib.rs@@ -7,19 +7,22 @@//! 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), and its MeshShaderPass draws by task and mesh shaders-//! (shader_advanced/mesh_shader_intro, mesh_shader.rs).+//! (shader_advanced/mesh_shader_intro, mesh_shader.rs), and its DepthCopy copies its depth into an image a Material+//! samples (shader_advanced/render_depth_to_texture, depth_copy.rs).use bevy::camera::visibility::{self, VisibilityClass};use bevy::prelude::*;use bevy::render::extract_component::{ExtractComponent, ExtractComponentPlugin};use bevy::render::RenderApp;+mod depth_copy;mod draw;mod gbuffer;mod instances;mod mesh_pass;mod mesh_shader;+pub use depth_copy::DepthCopy;pub use gbuffer::GBufferPass;pub use instances::ShaderInstances;pub use mesh_pass::MeshPass;@@ -127,6 +130,7 @@ pub fn install(app: &mut App) {instances::install(app);gbuffer::install(app);mesh_shader::install(app);+ depth_copy::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/shader/src/own.rs b/systems/shader/src/own.rsindex ac825455..3a0c9ec5 100644--- a/systems/shader/src/own.rs+++ b/systems/shader/src/own.rs@@ -90,6 +90,11 @@ pub struct OwnMaterial {b0: Handle<ShaderBuffer>,#[storage(54, read_only)]b1: Handle<ShaderBuffer>,+ // its depth texture and comparison sampler (ui_bind.rs DEPTH): a 1 x 1 depth image when it binds none, as Bevy has no+ // depth fallback image+ #[texture(55, sample_type = "depth")]+ #[sampler(56, sampler_type = "comparison")]+ depth: Option<Handle<Image>>,/// what its uniforms and buffers are packed from, for a frame's new values (own_live.rs)pub(crate) packing: Arc<Packing>,shader: u128,@@ -278,7 +283,7 @@ pub fn build(world: &mut World, v: &Value, image: &mut impl FnMut(&mut World, &Vlet ins = Inputs::read(world, &rest, what, image)?;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)) {+ if let Some((k, _)) = ins.textures.iter().find(|(k, _)| !textures.contains(k) && !others.contains(&((*k).clone(), "depth"))) {return Err(format!("{path} has no texture_2d {k}"));}// a texture the source declares and the spec doesn't give is Bevy's fallback image, as an Option<Handle<Image>>@@ -336,8 +341,12 @@ pub fn build(world: &mut World, v: &Value, image: &mut impl FnMut(&mut World, &V}let constants = intern(constants);let [t0, t1, t2, t3] = t;+ let depth = Some(match others.iter().find(|o| o.1 == "depth").and_then(|(n, _)| ins.textures.iter().find(|(k, _)| k == n)) {+ Some((_, h)) => h.clone(),+ None => no_depth(world),+ });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, b0: b[0].clone(), b1: b[1].clone(), packing, shader, vertex, alpha, depth_bias, cull, constants, layout: layout_of(own.get("vertex_attributes"))? })+ Ok(OwnMaterial { u0, u1, u2, u3, u4, u5, u6, u7, t0, t1, t2, t3, d1, d2a, cube, cube_array, d3, depth, b0: b[0].clone(), b1: b[1].clone(), packing, shader, vertex, alpha, depth_bias, cull, constants, layout: layout_of(own.get("vertex_attributes"))? })}/// Bevy's AlphaMode as the SDK writes it: "Opaque", "Blend", {"Mask": cutoff}, "Premultiplied", "AlphaToCoverage",@@ -361,6 +370,28 @@ fn alpha_mode(v: Option<&Value>) -> Result<Option<AlphaMode>, String> {}))}+/// A depth image a shader samples (texture_depth_2d with a sampler_comparison): Depth32Float, its sampler comparing+/// Always, as Bevy's render_depth_to_texture makes the image its depth-only camera's depth is copied into.+pub fn depth_image(w: u32, h: u32) -> Image {+ use bevy::image::{ImageCompareFunction, ImageSampler, ImageSamplerDescriptor};+ use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};+ let mut img = Image::new_uninit(Extent3d { width: w, height: h, depth_or_array_layers: 1 }, TextureDimension::D2, TextureFormat::Depth32Float, bevy::asset::RenderAssetUsages::default());+ img.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor { compare: Some(ImageCompareFunction::Always), ..default() });+ img+}++/// The 1 x 1 depth image every Material that binds no depth texture binds (made once).+fn no_depth(world: &mut World) -> Handle<Image> {+ #[derive(Resource)]+ struct NoDepth(Handle<Image>);+ if let Some(h) = world.get_resource::<NoDepth>() {+ return h.0.clone();+ }+ let h = world.resource_mut::<Assets<Image>>().add(depth_image(1, 1));+ world.insert_resource(NoDepth(h.clone()));+ h+}+/// A picture file decoded now as an Image (sRGB, the default sampler, as asset_server.load reads a colour texture), so/// the first frame that draws it has it.pub fn picture(world: &mut World, path: &str) -> Result<Handle<Image>, String> {diff --git a/systems/shader/wgsl/src/ui_bind.rs b/systems/shader/wgsl/src/ui_bind.rsindex a79d6a7f..35a6f5b7 100644--- a/systems/shader/wgsl/src/ui_bind.rs+++ b/systems/shader/wgsl/src/ui_bind.rs@@ -13,6 +13,9 @@ pub const DIMS: [(&str, &str, usize); 5] = [("texture_1d<", "1d", 16), ("texturepub 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 Material's depth texture (`dims`): its texture_depth_2d at 25 and its sampler_comparison at 26 (Bevy's+/// render_depth_to_texture samples a camera's depth so).+pub const DEPTH: [usize; 2] = [25, 26];/// Where a Material's slots (`dims`) start: past a sprite's own bindings (0 to 2, 10 when bindless), whose group a/// SpriteMaterial's share (shader/sprite_material). A UiMaterial's start at 0.pub const OWN_BASE: usize = 30;@@ -101,6 +104,13 @@ pub fn rebind_with(src: &str, groups: &[&str], what: &str, dims: bool, place: &dreturn Err(format!("{what} binds at most {max_samplers} samplers, {name} is one more"));}UNIFORMS + 2 * (samplers - 1) + 1+ } else if dims && (ty == "texture_depth_2d" || ty == "sampler_comparison") {+ let (d, slot) = if ty == "sampler_comparison" { ("comparison", DEPTH[1]) } else { ("depth", DEPTH[0]) };+ if others.iter().any(|(_, o)| *o == d) {+ return Err(format!("{what} binds one {ty}, {name} is a second"));+ }+ others.push((name.clone(), d));+ slot} else if let Some(&(_, d, slot)) = DIMS.iter().find(|(p, ..)| dims && ty.starts_with(p)) {if others.iter().any(|(_, o)| *o == d) {return Err(format!("{what} binds one texture_{d}, {name} is a second"));@@ -217,4 +227,14 @@ fn f() { @if(BINDLESS) let x = 1; }assert!(rebind_in(&src, &["3"], "a UiMaterial", false).unwrap_err().contains("texture_1d"));assert!(rebind_in("@group(3) @binding(0) var a: texture_3d<f32>;\n@group(3) @binding(1) var b: texture_3d<f32>;", &["3"], "a Material", true).unwrap_err().contains("a second"));}++ #[test]+ fn a_materials_depth_texture_and_comparison_sampler_go_to_their_slots() {+ // Bevy's show_depth_texture_material.wesl+ let src = "@group(3) @binding(0) var depth_texture: texture_depth_2d;\n@group(3) @binding(1) var depth_sampler: sampler_comparison;\n";+ let r = rebind_in(src, &["3"], "a Material", true).unwrap();+ assert!(r.src.contains(&format!("@binding({}) var depth_texture", OWN_BASE + DEPTH[0])) && r.src.contains(&format!("@binding({}) var depth_sampler", OWN_BASE + DEPTH[1])), "{}", r.src);+ assert_eq!(r.others, vec![("depth_texture".to_string(), "depth"), ("depth_sampler".to_string(), "comparison")]);+ assert!(rebind_in(src, &["3"], "a UiMaterial", false).is_err());+ }}