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
Texture binding arrays in an own Material; Bevy parity for shader_advanced/texture_binding_array, exact
shinyobjectz894f9821b417
diff --git a/bench/bevy-parity/examples.list b/bench/bevy-parity/examples.listindex 70d6437a..b09b5281 100644--- a/bench/bevy-parity/examples.list+++ b/bench/bevy-parity/examples.list@@ -150,3 +150,4 @@ shader_advanced/manual_materialshader_advanced/mesh_shader_introshader_advanced/render_depth_to_textureshader_advanced/specialized_mesh_pipeline+shader_advanced/texture_binding_arraydiff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsvindex 79e12e4c..42402a12 100644--- a/bench/bevy-parity/runs.tsv+++ b/bench/bevy-parity/runs.tsv@@ -149,3 +149,4 @@ shader_advanced/manual_material - 5,10,30shader_advanced/mesh_shader_intro - 5,10,30,60,120,240,300shader_advanced/render_depth_to_texture - 5,10,30,60shader_advanced/specialized_mesh_pipeline - 5,10+shader_advanced/texture_binding_array - 5,10diff --git a/docs/bevy-parity.md b/docs/bevy-parity.mdindex 3a4eabd6..a58a4a93 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 **150**, passing **150**, excluded **17** (docs/bevy-parity/excluded.tsv), left **271**.+Examples: **438**, ported **151**, passing **151**, excluded **17** (docs/bevy-parity/excluded.tsv), left **270**.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.@@ -255,6 +255,8 @@ doesn't pay.| 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 | || shader_advanced/specialized_mesh_pipeline | 10 | 1.000000 | 0 | 0 / 0 | 447 / 532 | 9 / 9 | 1 / 1 | 2.325 / 1.877 = 1.877 + 0 | yes | || shader_advanced/specialized_mesh_pipeline | 5 | 1.000000 | 0 | 0 / 0 | 445 / 532 | 9 / 9 | 1 / 1 | 46.496 / 2.986 = 2.986 + 0 | yes | |+| shader_advanced/texture_binding_array | 10 | 1.000000 | 0 | 0 / 0 | 447 / 535 | 6 / 8 | 1 / 2 | 1.737 / 2.273 = 2.273 + 0 | yes | |+| shader_advanced/texture_binding_array | 5 | 1.000000 | 0 | 0 / 0 | 447 / 535 | 6 / 8 | 1 / 2 | 36.278 / 2.279 = 2.279 + 0 | yes | |## Excludeddiff --git a/docs/bevy-parity/results.jsonl b/docs/bevy-parity/results.jsonlindex 5d58a02c..fce08425 100644--- a/docs/bevy-parity/results.jsonl+++ b/docs/bevy-parity/results.jsonl@@ -242,3 +242,5 @@{"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":""}{"example":"shader_advanced/specialized_mesh_pipeline","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.2500 0.2500 0.0000","0.5000 0.3750 0.0000"],"frame":10,"frame_ms":2.325,"materials":1,"mesh_entities":4,"meshes":9,"other_material":4,"visible":4},"raea":{"frame":17,"entities":532,"mesh_entities":4,"visible":4,"meshes":9,"materials":1,"batch_keys":0,"other_material":4,"extents":["0.2500 0.2500 0.0000","0.5000 0.3750 0.0000"],"frame_ms":1.877,"step_ms":null,"cost_ms":1.877},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}{"example":"shader_advanced/specialized_mesh_pipeline","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":445,"extents":["0.2500 0.2500 0.0000","0.5000 0.3750 0.0000"],"frame":5,"frame_ms":46.496,"materials":1,"mesh_entities":4,"meshes":9,"other_material":4,"visible":4},"raea":{"frame":12,"entities":532,"mesh_entities":4,"visible":4,"meshes":9,"materials":1,"batch_keys":0,"other_material":4,"extents":["0.2500 0.2500 0.0000","0.5000 0.3750 0.0000"],"frame_ms":2.986,"step_ms":null,"cost_ms":2.986},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/texture_binding_array","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":10,"frame_ms":1.737,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":18,"entities":535,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":2.273,"step_ms":null,"cost_ms":2.273},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}+{"example":"shader_advanced/texture_binding_array","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":447,"extents":["0.5000 0.5000 0.5000"],"frame":5,"frame_ms":36.278,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":13,"entities":535,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":0,"other_material":1,"extents":["0.5000 0.5000 0.5000"],"frame_ms":2.279,"step_ms":null,"cost_ms":2.279},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}diff --git a/sdk/raea/bench/bevy-parity/shader_advanced/texture_binding_array.tsx b/sdk/raea/bench/bevy-parity/shader_advanced/texture_binding_array.tsxnew file mode 100644index 00000000..f382e5c5--- /dev/null+++ b/sdk/raea/bench/bevy-parity/shader_advanced/texture_binding_array.tsx@@ -0,0 +1,29 @@+// Bevy v0.20.0 examples/shader_advanced/texture_binding_array.rs in raea's TSX (docs/control.feature FC2d): a+// BindlessMaterial of 16 pictures bound as one binding_array<texture_2d<f32>> and drawn by+// assets/shaders/texture_binding_array.wesl as written, each face of a default Cuboid (1 m) split 4 x 4 into the 16+// tiles, the textures/rpg/tiles pictures of TILE_ID in order, sampled with nearest filtering (ImagePlugin's+// default_nearest, whose fallback sampler the example binds as nearest_sampler); the camera at (2, 2, 2) looking at+// the origin, in Bevy's default 1280 x 720 window.+import { Composition, registerRoot, staticFile } from "raea";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d } from "raea/mesh";+import { Transform } from "raea/transform";+import { Material } from "@raea/render/bevy3d";++const TILE_ID = [19, 23, 4, 33, 12, 69, 30, 48, 10, 65, 40, 47, 57, 41, 44, 46];+const NEAREST = { filter: "nearest", mipmap: "nearest", wrap: "clamp" } as const;+const TILES = TILE_ID.map((id) => ({ src: staticFile(`textures/rpg/tiles/generic-rpg-tile${String(id).padStart(2, "0")}.png`), sampler: NEAREST }));++function Shot() {+ return (+ <>+ <Mesh3d>+ <Cuboid half_size={[0.5, 0.5, 0.5]} />+ <Material fragment={staticFile("shaders/texture_binding_array.wesl")} textures={{ textures: TILES }} />+ </Mesh3d>+ <Camera3d transform={Transform.fromXyz(2, 2, 2).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/materials.tsx b/sdk/render/src/3d/materials.tsxindex 7549f200..c994f7fb 100644--- a/sdk/render/src/3d/materials.tsx+++ b/sdk/render/src/3d/materials.tsx@@ -104,6 +104,9 @@ export interface MeshStandardMaterialProps extends SurfaceDrawProps {* imported. Shadows, depth and the prepass stay the standard surface's. */const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;+/** A texture a shader binds: an asset path, "render:NAME", or a picture with its sampler ({ src, sampler }). */+export type ShaderTexture = string | Record<string, unknown>;+export interface SurfaceShaderSpec {/** the source in WESL (Bevy 0.20's shader language, a superset of WGSL) */wesl?: string;@@ -119,8 +122,10 @@ export interface SurfaceShaderSpec {uniforms?: Record<string, number | number[] | string>;/** up to 4: an asset path, a picture made in code ({ width, height, pixels }) or "render:NAME"; with a sampler,* { src, sampler } (or a picture with its `sampler`). One more may be an array, read as texture_2d_array<f32> by- * layer: { layers: [picture, ...] } (one size and format) or { src, layers: N } (N layers stacked top to bottom) */- textures?: Record<string, string | Record<string, unknown>>;+ * layer: { layers: [picture, ...] } (one size and format) or { src, layers: N } (N layers stacked top to bottom). A+ * <Material>'s may also bind one binding_array<texture_2d<f32>>, a list of 1 to 16 pictures (Bevy's+ * texture_binding_array; a GPU without texture binding arrays refuses it) */+ textures?: Record<string, ShaderTexture | ShaderTexture[]>;/** shader defs: each NAME a WESL condition for `@if(NAME)` (a number is true), and a whole number also* `constants::NAME`; each set of defs compiles its own pipeline */defs?: ShaderDefs;@@ -206,13 +211,21 @@ export function surfaceShader(owner: string, sh: SurfaceShaderSpec, hook: RegExp// a picture's path found as the fragment's is (staticFile's /media/x); "render:NAME", data: URLs and pictures made in// code kept as givenconst file = (s: unknown) => (typeof s === "string" && !s.includes(":") ? assetPath(s) : s);- const found = Object.fromEntries(Object.entries(textures).map(([k, t]) => [k, typeof t === "string" ? file(t) : t !== null && typeof t === "object" && "src" in t ? { ...t, src: file(t.src) } : t]));+ const one = (t: ShaderTexture) => (typeof t === "string" ? file(t) : t !== null && typeof t === "object" && "src" in t ? { ...t, src: file(t.src) } : t);+ const found = Object.fromEntries(Object.entries(textures).map(([k, t]) => [k, Array.isArray(t) ? t.map(one) : one(t)]));return { ...(fragment !== undefined ? { fragment: assetPath(fragment) } : wesl !== undefined ? { wesl } : { wgsl }), uniforms, textures: found, ...(defs !== undefined ? { defs: shaderDefs(owner, defs) } : {}), ...(own !== undefined ? { own, ...(own.vertex !== undefined ? { vertex: assetPath(own.vertex) } : {}), ...(buffers !== undefined ? { buffers } : {}) } : {}) };}/** A shader's textures checked: up to 4 pictures and one array (docs/shaders.feature SH9). */-export function checkTextures(owner: string, textures: Record<string, string | Record<string, unknown>>): void {- const ts = Object.keys(textures);+export function checkTextures(owner: string, textures: Record<string, ShaderTexture | ShaderTexture[]>): void {+ const lists = Object.keys(textures).filter((k) => Array.isArray(textures[k]));+ if (lists.length > 1) throw new RangeError(`${owner}: a shader has one binding_array, got ${lists.join(", ")}`);+ for (const k of lists) {+ const l = textures[k] as ShaderTexture[];+ if (l.length < 1 || l.length > 16) throw new RangeError(`${owner}: binding_array ${k} takes 1 to 16 pictures, got ${l.length}`);+ for (const t of l) if (typeof t === "object" && t !== null && t.sampler !== undefined) samplerSpec(`${owner}: texture ${k}`, t.sampler as SamplerSpec);+ }+ const ts = Object.keys(textures).filter((k) => !lists.includes(k));const arrays = ts.filter((k) => typeof textures[k] === "object" && textures[k] !== null && "layers" in (textures[k] as object));if (arrays.length > 1) throw new RangeError(`${owner}: a shader has one texture array, got ${arrays.join(", ")}`);if (ts.length - arrays.length > 4) throw new RangeError(`${owner}: a shader has at most 4 textures (and one array), got ${ts.length - arrays.length}`);diff --git a/systems/shader/src/lib.rs b/systems/shader/src/lib.rsindex ff79db2a..e0c2b27e 100644--- a/systems/shader/src/lib.rs+++ b/systems/shader/src/lib.rs@@ -34,6 +34,8 @@ pub use layout::slots as uniform_slots;/// A storage buffer's words in its WGSL type's storage layout (a compute as written's own: raea-sys-compute slab.rs).pub use storage_layout::words as storage_words;pub mod own;+pub mod own_array;+mod own_images;pub mod own_live;pub mod ui;use raea_sys_shader_wgsl::ui_bind;@@ -203,6 +205,8 @@ pub struct Inputs {pub textures: Vec<(String, Handle<Image>)>,/// the one texture array, `{layers}` (raea-sys-sampler's arrays)pub array: Option<(String, Handle<Image>)>,+ /// the one binding_array<texture_2d<f32>>, a list of pictures (own.rs, Bevy's texture_binding_array)+ pub bindings: Option<(String, Vec<Handle<Image>>)>,pub defs: Vec<ShaderDefVal>,}@@ -226,11 +230,20 @@ impl Inputs {}let mut textures = vec![];let mut array = None;+ let mut bindings = None;if let Some(t) = o.get("textures") {for (k, x) in t.as_object().ok_or_else(|| format!("{what}'s textures are {{name: picture}}"))? {if !ident(k) {return Err(format!("a texture's name is a WGSL identifier, got {k:?}"));}+ if let Some(list) = x.as_array() {+ if bindings.is_some() {+ return Err(format!("{what} has one binding_array, got a second ({k})"));+ }+ let pics = list.iter().enumerate().map(|(i, p)| raea_sys_sampler::texture(world, p, &format!("{what} texture {k}[{i}]"), image).map_err(|e| format!("texture {k}[{i}]: {e}")));+ bindings = Some((k.clone(), pics.collect::<Result<Vec<_>, _>>()?));+ continue;+ }if raea_sys_sampler::arrays::is_array(x) {if array.is_some() {return Err(format!("{what} has one texture array, got a second ({k})"));@@ -244,7 +257,7 @@ impl Inputs {if textures.len() > TEXTURES {return Err(format!("{what} has at most {TEXTURES} textures, got {}", textures.len()));}- Ok(Inputs { src, uniforms, textures, array, defs: defs(o, what)? })+ Ok(Inputs { src, uniforms, textures, array, bindings, defs: defs(o, what)? })}/// The uniforms' names and WGSL types, and the textures' names.diff --git a/systems/shader/src/own.rs b/systems/shader/src/own.rsindex 3a0c9ec5..b1492e86 100644--- a/systems/shader/src/own.rs+++ b/systems/shader/src/own.rs@@ -27,9 +27,10 @@ use serde_json::Value;use crate::own_live::{storage, Packing};use crate::ui_bind::{rebind_in, Rebound};use crate::{layout, register, Inputs, OwnSurface, Shaded};+pub use crate::own_images::{depth_image, picture};/// The fragment shader every pipeline starts from, swapped in `specialize` for the material's own (its uuid).-const PLACEHOLDER: Handle<Shader> = uuid_handle!("5d1e7a3c-2b9f-4e6d-8a1c-3f7b9d2e6c41");+pub(crate) const PLACEHOLDER: Handle<Shader> = uuid_handle!("5d1e7a3c-2b9f-4e6d-8a1c-3f7b9d2e6c41");const STUB: &str = "import bevy_pbr::render::forward_io::VertexOutput;\n@fragment\nfn fragment(in: VertexOutput) -> @location(0) vec4<f32> { return vec4(1.0, 0.0, 1.0, 1.0); }\n";/// The same for a 2D one (Material2d's), whose vertex output is mesh2d's.const PLACEHOLDER_2D: Handle<Shader> = uuid_handle!("5d1e7a3c-2b9f-4e6d-8a1c-3f7b9d2e6c42");@@ -95,14 +96,16 @@ pub struct OwnMaterial {#[texture(55, sample_type = "depth")]#[sampler(56, sampler_type = "comparison")]depth: Option<Handle<Image>>,+ /// its binding_array<texture_2d<f32>>'s pictures, bound by the OwnArrayMaterial wrapping it (own_array.rs)+ pub(crate) array: Vec<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,/// the vertex shader's uuid, 0 for Bevy's mesh vertex shadervertex: u128,/// None when the spec gives none: Opaque as a Material's, a sprite's own as a SpriteMaterial's- alpha: Option<AlphaMode>,- depth_bias: f32,+ pub(crate) alpha: Option<AlphaMode>,+ pub(crate) depth_bias: f32,/// the faces it culls (the pipeline's primitive.cull_mode); None keeps the pipeline's (3D culls Back, 2D none)cull: Option<Option<Face>>,/// its fragment stage's pipeline-overridable constants (WGSL `override`): their hash in CONSTANTS, 0 for none@@ -243,7 +246,7 @@ fn alpha2d(a: AlphaMode) -> AlphaMode2d {/// A pipeline given the material's own shaders: its fragment where it is `placeholder`, its vertex shader (if any) in/// that same pipeline (the main pass's: the prepass and shadow pipelines keep Bevy's), the faces it culls, and its/// fragment's pipeline-overridable constants (as Bevy's pipeline_constants pushes LEVELS in its specialize).-fn swap(descriptor: &mut RenderPipelineDescriptor, layout: &MeshVertexBufferLayoutRef, placeholder: &Handle<Shader>, k: OwnKey) -> Result<(), SpecializedMeshPipelineError> {+pub(crate) fn swap(descriptor: &mut RenderPipelineDescriptor, layout: &MeshVertexBufferLayoutRef, placeholder: &Handle<Shader>, k: OwnKey) -> Result<(), SpecializedMeshPipelineError> {let Some(f) = descriptor.fragment.as_mut().filter(|f| f.shader.id() == placeholder.id()) else { return Ok(()) };let shader = |id: u128| Handle::Uuid(bevy::asset::uuid::Uuid::from_u128(id), core::marker::PhantomData);f.shader = shader(k.shader);@@ -265,7 +268,7 @@ fn swap(descriptor: &mut RenderPipelineDescriptor, layout: &MeshVertexBufferLayopub fn install(app: &mut App) {let _ = app.world_mut().resource_mut::<Assets<Shader>>().insert(&PLACEHOLDER, Shader::from_wesl(STUB, "embedded://raea_sys_shader/own_placeholder.wesl"));let _ = app.world_mut().resource_mut::<Assets<Shader>>().insert(&PLACEHOLDER_2D, Shader::from_wesl(STUB_2D, "embedded://raea_sys_shader/own_placeholder_2d.wesl"));- app.add_plugins((MaterialPlugin::<OwnMaterial>::default(), Material2dPlugin::<OwnMaterial>::default(), SpriteMaterialPlugin::<OwnMaterial>::default()));+ app.add_plugins((MaterialPlugin::<OwnMaterial>::default(), MaterialPlugin::<crate::own_array::OwnArrayMaterial>::default(), Material2dPlugin::<OwnMaterial>::default(), SpriteMaterialPlugin::<OwnMaterial>::default()));}/// The material a `<Material>` spec asks for: {fragment, vertex?, uniforms, textures, defs, own: {alpha_mode,@@ -340,13 +343,14 @@ pub fn build(world: &mut World, v: &Value, image: &mut impl FnMut(&mut World, &Vconstants.push((k.clone(), n));}let constants = intern(constants);+ let array = crate::own_images::array(world, ins.bindings.as_ref(), &others, textures.is_empty(), !packing.uniforms.is_empty(), &mut t[0], two_d, path)?;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),+ None => crate::own_images::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, depth, 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, array, 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",@@ -370,39 +374,6 @@ 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> {- use bevy::asset::RenderAssetUsages;- use bevy::image::{CompressedImageFormats, ImageSampler, ImageType};- let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;- let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("png");- let image = Image::from_buffer(&bytes, ImageType::Extension(ext), CompressedImageFormats::NONE, true, ImageSampler::Default, RenderAssetUsages::default()).map_err(|e| format!("{path}: {e}"))?;- Ok(world.resource_mut::<Assets<Image>>().add(image))-}-/// 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.pub fn folder(world: &mut World, path: &str, src: &str) -> Result<String, String> {@@ -479,7 +450,13 @@ pub fn shared(world: &mut World, v: &Value, image: &mut impl FnMut(&mut World, &/// kept aside as `Shaded` (so the rows' sync finds it) and the scene's <SurfaceShader> kept off it.pub fn put(world: &mut World, e: Entity, h: Handle<OwnMaterial>) -> Result<(), String> {let Some(std) = world.get::<MeshMaterial3d<StandardMaterial>>(e).map(|m| m.0.clone()) else { return Ok(()) };- world.entity_mut(e).remove::<MeshMaterial3d<StandardMaterial>>().insert((MeshMaterial3d(h), Shaded { std }, OwnSurface));+ let array = crate::own_array::wrap(world, &h);+ let mut w = world.entity_mut(e);+ w.remove::<MeshMaterial3d<StandardMaterial>>().insert((Shaded { std }, OwnSurface));+ match array {+ Some(a) => w.insert(MeshMaterial3d(a)),+ None => w.insert(MeshMaterial3d(h)),+ };crate::own_live::settle(world, e)}diff --git a/systems/shader/src/own_array.rs b/systems/shader/src/own_array.rsnew file mode 100644index 00000000..24db0ad1--- /dev/null+++ b/systems/shader/src/own_array.rs@@ -0,0 +1,103 @@+//! An own Material with a binding_array<texture_2d<f32>> (docs/control.feature FC2d, Bevy's+//! shader_advanced/texture_binding_array): OwnMaterial's bind group but its uniform buffers (wgpu has no binding array beside one), with the array at ui_bind's ARRAY slot, its+//! pictures (own_images.rs) in order and Bevy's fallback image in the slots past them, as Bevy's example binds its+//! BindlessMaterial. Bevy's derive can't own a texture array, so this type builds its bind group directly. Its+//! pipelines are OwnMaterial's: the same key, shaders and specialize.++use std::num::NonZero;++use bevy::ecs::system::lifetimeless::SRes;+use bevy::ecs::system::SystemParamItem;+use bevy::mesh::MeshVertexBufferLayoutRef;+use bevy::pbr::{Material, MaterialPipeline, MaterialPipelineKey};+use bevy::prelude::*;+use bevy::render::render_asset::RenderAssets;+use bevy::render::render_resource::{+ AsBindGroup, AsBindGroupError, BindGroupBuilder, BindGroupEntry, BindGroupLayout, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingResources, BindingType, BufferBindingType, PipelineCache, PreparedBindGroup, RenderPipelineDescriptor, ShaderStages,+ SpecializedMeshPipelineError, TextureSampleType, TextureViewDimension,+};+use bevy::render::renderer::RenderDevice;+use bevy::render::storage::GpuShaderBuffer;+use bevy::render::material_bind_groups::FallbackBuffer;+use bevy::render::texture::{FallbackImage, GpuImage};+use bevy::shader::ShaderRef;++use crate::own::{OwnKey, OwnMaterial, PLACEHOLDER};+use crate::ui_bind::{ARRAY, ARRAY_LEN, OWN_BASE};++/// An OwnMaterial whose source binds a texture array, its pictures `own.array`.+#[derive(Asset, TypePath, Clone, Debug)]+pub struct OwnArrayMaterial {+ pub own: OwnMaterial,+}++const BINDING: u32 = (OWN_BASE + ARRAY) as u32;++impl AsBindGroup for OwnArrayMaterial {+ type Data = OwnKey;+ type Param = (<OwnMaterial as AsBindGroup>::Param, SRes<RenderAssets<GpuImage>>, SRes<FallbackImage>);++ fn label() -> &'static str {+ "raea_own_array_material"+ }++ fn bind_group_data(&self) -> OwnKey {+ self.own.bind_group_data()+ }++ fn as_bind_group(&self, layout: &BindGroupLayoutDescriptor, device: &RenderDevice, cache: &PipelineCache, fallback_buffer: &FallbackBuffer, buffers: &RenderAssets<GpuShaderBuffer>, (inner, images, fallback): &mut SystemParamItem<'_, '_, Self::Param>) -> Result<PreparedBindGroup, AsBindGroupError> {+ let layout = cache.get_bind_group_layout(layout);+ let mut b = BindGroupBuilder::default();+ self.own.build_bind_group(&layout, device, inner, true, &mut b)?;+ let mut views = vec![&*fallback.d2.texture_view; ARRAY_LEN];+ for (i, h) in self.own.array.iter().take(ARRAY_LEN).enumerate() {+ views[i] = &*images.get(h).ok_or(AsBindGroupError::RetryNextUpdate)?.texture_view;+ }+ let keep: Vec<u32> = Self::bind_group_layout_entries(device, true).iter().map(|e| e.binding).collect();+ let mut entries: Vec<BindGroupEntry> = b.binding_resources.iter().filter(|(i, _)| keep.contains(i)).map(|(i, r)| BindGroupEntry { binding: *i, resource: r.get_binding(fallback_buffer, buffers) }).collect();+ entries.push(BindGroupEntry { binding: BINDING, resource: BindingResource::TextureViewArray(&views) });+ Ok(PreparedBindGroup { bindings: BindingResources(vec![]), bind_group: device.create_bind_group(Self::label(), &layout, &entries) })+ }++ fn build_bind_group(&self, _: &BindGroupLayout, _: &RenderDevice, _: &mut SystemParamItem<'_, '_, Self::Param>, _: bool, _: &mut BindGroupBuilder) -> Result<(), AsBindGroupError> {+ // an array of views can't be owned, so `as_bind_group` builds it (as Bevy's texture_binding_array does)+ Err(AsBindGroupError::CreateBindGroupDirectly)+ }++ fn bind_group_layout_entries(device: &RenderDevice, _: bool) -> Vec<BindGroupLayoutEntry> {+ // wgpu refuses a binding array beside a uniform buffer, so this one binds none (own_images.rs refuses uniforms)+ let mut e = OwnMaterial::bind_group_layout_entries(device, true);+ e.retain(|e| !matches!(e.ty, BindingType::Buffer { ty: BufferBindingType::Uniform, .. }));+ let ty = BindingType::Texture { sample_type: TextureSampleType::Float { filterable: true }, view_dimension: TextureViewDimension::D2, multisampled: false };+ e.push(BindGroupLayoutEntry { binding: BINDING, visibility: ShaderStages::FRAGMENT, ty, count: NonZero::new(ARRAY_LEN as u32) });+ e+ }+}++impl Material for OwnArrayMaterial {+ fn fragment_shader() -> ShaderRef {+ ShaderRef::Handle(PLACEHOLDER)+ }+ fn alpha_mode(&self) -> AlphaMode {+ self.own.alpha.unwrap_or(AlphaMode::Opaque)+ }+ fn depth_bias(&self) -> f32 {+ <OwnMaterial as Material>::depth_bias(&self.own)+ }+ fn specialize(_: &MaterialPipeline, descriptor: &mut RenderPipelineDescriptor, layout: &MeshVertexBufferLayoutRef, key: MaterialPipelineKey<Self>) -> Result<(), SpecializedMeshPipelineError> {+ crate::own::swap(descriptor, layout, &PLACEHOLDER, key.bind_group_data)+ }+}++/// The array Material wrapping a part's OwnMaterial, made once per OwnMaterial; None when it binds no array.+pub(crate) fn wrap(world: &mut World, h: &Handle<OwnMaterial>) -> Option<Handle<OwnArrayMaterial>> {+ #[derive(Resource, Default)]+ struct Wrapped(std::collections::HashMap<AssetId<OwnMaterial>, Handle<OwnArrayMaterial>>);+ if let Some(a) = world.get_resource_or_init::<Wrapped>().0.get(&h.id()).cloned() {+ return Some(a);+ }+ let own = world.resource::<Assets<OwnMaterial>>().get(h).filter(|m| !m.array.is_empty())?.clone();+ let a = world.resource_mut::<Assets<OwnArrayMaterial>>().add(OwnArrayMaterial { own });+ world.get_resource_or_init::<Wrapped>().0.insert(h.id(), a.clone());+ Some(a)+}diff --git a/systems/shader/src/own_images.rs b/systems/shader/src/own_images.rsnew file mode 100644index 00000000..e739db2b--- /dev/null+++ b/systems/shader/src/own_images.rs@@ -0,0 +1,75 @@+//! The pictures an own Material (own.rs) binds besides its four textures: a depth image (Bevy's render_depth_to_texture)+//! and a binding_array<texture_2d<f32>>'s list (Bevy's texture_binding_array, drawn by own_array.rs), and a picture file+//! decoded at once.++use bevy::prelude::*;+use bevy::render::render_resource::WgpuFeatures;+use bevy::render::renderer::RenderDevice;++use crate::ui_bind::ARRAY_LEN;++/// A binding_array<texture_2d<f32>>'s pictures, the spec's list (`bindings`) for the source's `others` binding_array:+/// in 3D only, on a device with texture binding arrays, at most ARRAY_LEN. A source that declares no texture_2d samples+/// with its first sampler, the first texture's, so `t0` becomes the list's first picture and that sampler its own.+pub(crate) fn array(world: &World, bindings: Option<&(String, Vec<Handle<Image>>)>, others: &[(String, &'static str)], no_textures: bool, uniforms: bool, t0: &mut Option<Handle<Image>>, two_d: bool, path: &str) -> Result<Vec<Handle<Image>>, String> {+ let declared = others.iter().find(|o| o.1 == "binding_array").map(|o| o.0.as_str());+ let Some((name, list)) = bindings else {+ return match declared {+ Some(n) => Err(format!("{path}'s binding_array {n} has no list of pictures")),+ None => Ok(vec![]),+ };+ };+ if declared != Some(name.as_str()) {+ return Err(format!("{path} has no binding_array<texture_2d<f32>> {name}"));+ }+ if uniforms {+ return Err(format!("{path}: a binding_array can't sit beside uniforms in one bind group (wgpu); give its values as a storage buffer"));+ }+ if two_d {+ return Err(format!("{path}: a binding_array is a 3D Material's, not a 2D one's"));+ }+ if list.is_empty() || list.len() > ARRAY_LEN {+ return Err(format!("{path}'s binding_array {name} takes 1 to {ARRAY_LEN} pictures, got {}", list.len()));+ }+ let need = WgpuFeatures::TEXTURE_BINDING_ARRAY | WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING;+ if world.get_resource::<RenderDevice>().is_some_and(|d| !d.features().contains(need)) {+ return Err(format!("{path}'s binding_array {name}: this GPU has no texture binding arrays"));+ }+ if no_textures {+ *t0 = Some(list[0].clone());+ }+ Ok(list.clone())+}++/// 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).+pub(crate) 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> {+ use bevy::asset::RenderAssetUsages;+ use bevy::image::{CompressedImageFormats, ImageSampler, ImageType};+ let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;+ let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("png");+ let image = Image::from_buffer(&bytes, ImageType::Extension(ext), CompressedImageFormats::NONE, true, ImageSampler::Default, RenderAssetUsages::default()).map_err(|e| format!("{path}: {e}"))?;+ Ok(world.resource_mut::<Assets<Image>>().add(image))+}diff --git a/systems/shader/src/own_live.rs b/systems/shader/src/own_live.rsindex f91dce3e..d885e773 100644--- a/systems/shader/src/own_live.rs+++ b/systems/shader/src/own_live.rs@@ -12,6 +12,7 @@ use serde_json::Value;use crate::layout;use crate::own::OwnMaterial;+use crate::own_array::OwnArrayMaterial;/// What a material's uniforms and buffers are packed from: its source as compiled (its struct types), its uniforms'/// and storage buffers' (name, WGSL type) in slot order, and its defs (a struct field under `@if`).@@ -47,22 +48,33 @@ fn handle<C: Component + std::ops::Deref<Target = Handle<OwnMaterial>>>(world: &world.get::<C>(e).map(|m| (**m).clone())}+/// What a Material's values are packed from, and its storage buffers.+fn packed(m: &OwnMaterial) -> (std::sync::Arc<Packing>, [Handle<ShaderBuffer>; 2]) {+ (m.packing.clone(), m.buffers())+}+/// An `own:uniforms` component row: the frame's {uniforms, buffers} packed into the part's own Material (3D, 2D or a/// sprite's) and its storage buffers.pub fn patch(world: &mut World, e: Entity, v: &Value) -> Result<(), String> {let h = [handle::<MeshMaterial3d<OwnMaterial>>(world, e), handle::<MeshMaterial2d<OwnMaterial>>(world, e), handle::<SpriteMaterial<OwnMaterial>>(world, e)];- let h = h.into_iter().flatten().next();- // a row applied before the part's Material is put on (shade_rows runs after the rows): kept for `put`- let Some(h) = h else {- world.entity_mut(e).insert(Pending(v.clone()));- return Ok(());+ let (h, arr) = (h.into_iter().flatten().next(), world.get::<MeshMaterial3d<OwnArrayMaterial>>(e).map(|m| m.0.clone()));+ let got = match (&h, &arr) {+ (Some(h), _) => world.resource::<Assets<OwnMaterial>>().get(h).map(packed),+ (None, Some(a)) => world.resource::<Assets<OwnArrayMaterial>>().get(a).map(|m| packed(&m.own)),+ // a row applied before the part's Material is put on (shade_rows runs after the rows): kept for `put`+ (None, None) => {+ world.entity_mut(e).insert(Pending(v.clone()));+ return Ok(());+ }};- let Some((p, bufs)) = world.resource::<Assets<OwnMaterial>>().get(&h).map(|m| (m.packing.clone(), m.buffers())) else { return Err("own:uniforms: its Material isn't made".into()) };+ let Some((p, bufs)) = got else { return Err("own:uniforms: its Material isn't made".into()) };if let Some(given) = v.get("uniforms").and_then(Value::as_object) {let slots = layout::slots(&p.src, &p.uniforms, given, &p.defs)?;- if let Some(mut m) = world.resource_mut::<Assets<OwnMaterial>>().get_mut(&h) {- m.set_slots(slots);- }+ match (h, arr) {+ (Some(h), _) => world.resource_mut::<Assets<OwnMaterial>>().get_mut(&h).map(|mut m| m.set_slots(slots)),+ (None, Some(a)) => world.resource_mut::<Assets<OwnArrayMaterial>>().get_mut(&a).map(|mut m| m.own.set_slots(slots)),+ (None, None) => None,+ };}let given = v.get("buffers").and_then(Value::as_object).cloned().unwrap_or_default();for ((name, ty), b) in p.storages.iter().zip(bufs) {diff --git a/systems/shader/wgsl/src/ui_bind.rs b/systems/shader/wgsl/src/ui_bind.rsindex 35a6f5b7..fd8b484c 100644--- a/systems/shader/wgsl/src/ui_bind.rs+++ b/systems/shader/wgsl/src/ui_bind.rs@@ -16,6 +16,10 @@ 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];+/// A Material's binding_array<texture_2d<f32>> (`dims`) at 27, of up to ARRAY_LEN pictures (Bevy's+/// texture_binding_array), where the device has texture binding arrays.+pub const ARRAY: usize = 27;+pub const ARRAY_LEN: usize = 16;/// 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;@@ -104,6 +108,12 @@ 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.replace(char::is_whitespace, "") == "binding_array<texture_2d<f32>>" {+ if others.iter().any(|(_, o)| *o == "binding_array") {+ return Err(format!("{what} binds one binding_array, {name} is a second"));+ }+ others.push((name.clone(), "binding_array"));+ ARRAY} 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) {@@ -237,4 +247,13 @@ fn f() { @if(BINDLESS) let x = 1; }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());}++ #[test]+ fn a_materials_texture_binding_array_goes_to_its_slot() {+ // Bevy's texture_binding_array.wesl: the array and a sampler with no texture_2d of its own+ let src = "@group(3) @binding(0) var textures: binding_array<texture_2d<f32>>;\n@group(3) @binding(1) var nearest_sampler: sampler;\n";+ let r = rebind_in(src, &["3"], "a Material", true).unwrap();+ assert!(r.src.contains(&format!("@binding({}) var textures", OWN_BASE + ARRAY)), "{}", r.src);+ assert_eq!((r.others, r.samplers), (vec![("textures".to_string(), "binding_array")], 1));+ }}