Render: save wood images with physical grain controls (#1599)

* Render: save wood images with physical grain controls

* Render: prepare plain glass before marking the GPU host ready
This commit is contained in:
selune
2026-11-05 04:49:46 +00:00
committed by GitHub
parent 6d2465b52d
commit 8691cefbbf
60 changed files with 5776 additions and 238 deletions
+1 -1
View File
@@ -51,7 +51,7 @@ fn aging_mask(layer: AgingLayer, point:vec3<f32>, normal:vec3<f32>)->vec2<f32> {
return vec2<f32>(clamp(coverage*layer.mask.x,0.0,1.0),field);
}
fn aged_surface(original:Triangle,point:vec3<f32>,outward:vec3<f32>)->Triangle {
if original.base.w>0.0 || original.interior.z>0.0 {return original;}
if original.base.w>0.0 || (u32(original.interior.z)&1u)!=0u {return original;}
var result=original;
for(var index=0u;index<8u;index+=1u) {
let layer=u.aging[index];
+1 -1
View File
@@ -35,7 +35,7 @@ impl Pipelines {
layout: Some(&guide_layout),
module: &guide_shader,
entry_point: Some("denoise_guides"),
compilation_options: Default::default(),
compilation_options: wgpu::PipelineCompilationOptions { constants: &[("HAS_TEXTURES", 1.0)], ..Default::default() },
cache: None,
});
let entries: Vec<_> = (0..4)
+8 -5
View File
@@ -16,17 +16,20 @@ fn denoise_guides(@builtin(global_invocation_id) gid: vec3<u32>) {
if u.environment.w>0.0 && emitter_hit_bounded(ray.origin,ray.direction,u.lighting.x).distance<hit.distance { return; }
var t=triangle(hit.triangle);
let position=surface_point(t,hit.bary);
t=texture_surface(t,position);
var geometric=unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz));
if dot(geometric,-ray.direction)<0.0 { geometric=-geometric; }
let map_record=texture_record(t.optics.w);
let gradients=texture_gradients(map_record,geometric,ray.direction,hit.distance,length(position-ray.origin),0u);
let mapped_surface=texture_surface(map_record,t.base.xyz,t.parameters.x,t.parameters.y,position,gradients,(u32(t.interior.z)&2u)!=0u);
t.base=vec4<f32>(mapped_surface.color,t.base.w);t.parameters=vec4<f32>(mapped_surface.metallic,mapped_surface.roughness,t.parameters.zw);
t=aged_surface(t,position,unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz)));
// Single first-hit guides cannot describe refracted or sharp reflected images.
if t.base.w>0.0 || (t.parameters.x>0.5 && t.parameters.y<0.25) || (t.coat.x>0.0 && t.coat.y<0.05) { return; }
var geometric=unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz));
if dot(geometric,-ray.direction)<0.0 { geometric=-geometric; }
var n=unit(t.n0.xyz*hit.bary.x+t.n1.xyz*hit.bary.y+t.n2.xyz*hit.bary.z);
if dot(n,geometric)<0.0 { n=-n; }
if dot(n,-ray.direction)<=0.0 { n=geometric; }
let mapped=texture_normal(t,position,n,geometric);
if dot(mapped,-ray.direction)>0.0 { n=mapped; }
let mapped_normal=texture_normal(map_record,mapped_surface.normal,n,geometric);
if dot(mapped_normal,-ray.direction)>0.0 { n=mapped_normal; }
let depth=dot(position-u.eye.xyz,-u.back.xyz);
var footprint=2.0*length(u.up.xyz)/f32(u.image.y);
if u.eye.w>0.5 { footprint*=max(depth,0.0)/u.back.w; }
+105 -21
View File
@@ -28,20 +28,32 @@ mod scene;
#[cfg(test)]
mod tests;
mod textures;
const SHADER: &str = concat!(
include_str!("path.wgsl"),
"\n",
include_str!("shadows.wgsl"),
"\n",
include_str!("textures.wgsl"),
"
",
include_str!("volume.wgsl"),
"
",
include_str!("aging.wgsl")
);
// Disjoint glass admits at most one active medium. Fixed local array sizes let
// native compilers discard the unused fifteen entries without changing nested
// transport's sixteen-medium limit. Both programs share every shader operation.
macro_rules! path_shader {
($capacity:literal) => {
concat!(
"const MEDIUM_CAPACITY: u32 = ",
$capacity,
"u;\n",
include_str!("path.wgsl"),
"\n",
include_str!("shadows.wgsl"),
"\n",
include_str!("textures.wgsl"),
"\n",
include_str!("volume.wgsl"),
"\n",
include_str!("aging.wgsl")
)
};
}
const SHADER: &str = path_shader!(16);
const SINGLE_MEDIUM_SHADER: &str = path_shader!(1);
const MAX_TRIANGLES: u64 = MAX_GPU_PATH_TRIANGLES;
const PATH_WORKGROUP_SIZE: u32 = 32;
const SCENE_PIPELINE_CACHE_SLOTS: usize = 5;
const PARAMETER_BYTES: usize = 1184;
// Eight u32 words: count low, pixel, bounce, sample, code, count high, first-writer flag, spare.
const FAILURE_BYTES: u64 = 32;
@@ -166,6 +178,9 @@ struct Context {
device: wgpu::Device,
queue: wgpu::Queue,
pipeline: wgpu::ComputePipeline,
// Plain opaque and non-nested glass are ready before the host is published.
// The four map/nested variants are prepared lazily in the remaining slots.
scene_pipelines: [std::sync::OnceLock<wgpu::ComputePipeline>; SCENE_PIPELINE_CACHE_SLOTS],
// Built and warmed by the first denoised job, then shared by later ones.
denoise: std::sync::OnceLock<denoise::Pipelines>,
layout: wgpu::BindGroupLayout,
@@ -184,6 +199,47 @@ impl Context {
fn wait(&self, submission: wgpu::SubmissionIndex, timeout: Duration) -> Result<()> {
wait_device(&self.device, &self.healthy, submission, timeout)
}
fn prepared_scene_pipeline(&self, opaque: bool, maps: bool, nested: bool) -> Result<&wgpu::ComputePipeline> {
let Some(index) = scene_pipeline_variant(opaque, maps, nested) else { return Ok(&self.pipeline) };
self.scene_pipelines.get(index).and_then(std::sync::OnceLock::get).ok_or_else(|| gpu("captured scene has no prepared pipeline"))
}
fn prepare_scene_pipeline(&self, opaque: bool, maps: bool, nested: bool) -> Result<&wgpu::ComputePipeline> {
self.ensure_available()?;
let Some(index) = scene_pipeline_variant(opaque, maps, nested) else { return Ok(&self.pipeline) };
let slot = self.scene_pipelines.get(index).ok_or_else(|| gpu("scene pipeline variant exceeds its finite cache"))?;
if let Some(pipeline) = slot.get() {
return Ok(pipeline);
}
let _compiling = one_compile_at_a_time();
if let Some(pipeline) = slot.get() {
return Ok(pipeline);
}
let scopes = scopes(&self.device);
let shader = self.device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("gpu-path captured scene"),
source: wgpu::ShaderSource::Wgsl(if opaque || nested { SHADER } else { SINGLE_MEDIUM_SHADER }.into()),
});
let layout = self.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("gpu-path captured scene"),
bind_group_layouts: &[Some(&self.layout)],
immediate_size: 0,
});
let pipeline = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("gpu-path captured scene"),
layout: Some(&layout),
module: &shader,
entry_point: Some("main"),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &[("OPAQUE_SCENE", f64::from(u8::from(opaque))), ("HAS_TEXTURES", f64::from(u8::from(maps)))],
..Default::default()
},
cache: None,
});
checked(scopes)?;
warm_up(&self.device, &self.queue, &pipeline, &placeholder_bind(&self.device, &self.layout, 7)?, &self.healthy)?;
let _ = slot.set(pipeline);
slot.get().ok_or_else(|| gpu("scene pipeline publication failed"))
}
}
fn wait_device(device: &wgpu::Device, healthy: &AtomicBool, submission: wgpu::SubmissionIndex, timeout: Duration) -> Result<()> {
@@ -248,13 +304,25 @@ impl Executor {
layout: Some(&pipeline_layout),
module: &shader,
entry_point: Some("main"),
compilation_options: Default::default(),
compilation_options: wgpu::PipelineCompilationOptions { constants: &[("OPAQUE_SCENE", 1.0)], ..Default::default() },
cache: None,
});
checked(scopes)?;
drop(compiling);
warm_up(&device, &queue, &pipeline, &placeholder_bind(&device, &layout, 7)?, &healthy)?;
Ok(Self { context: Arc::new(Context { healthy, device, queue, pipeline, layout, denoise: std::sync::OnceLock::new() }) })
let context = Arc::new(Context {
healthy,
device,
queue,
pipeline,
layout,
denoise: std::sync::OnceLock::new(),
scene_pipelines: std::array::from_fn(|_| std::sync::OnceLock::new()),
});
// The original host prepared glass before advertising readiness. Keep the
// common no-map/non-nested program out of the first image job's work.
context.prepare_scene_pipeline(false, false, false)?;
Ok(Self { context })
}
}
@@ -325,6 +393,16 @@ fn descriptor() -> Result<ExecutorDescriptor> {
})
}
fn scene_pipeline_variant(opaque: bool, maps: bool, nested: bool) -> Option<usize> {
if opaque { maps.then_some(0) } else { Some(1 + 2 * usize::from(maps) + usize::from(nested)) }
}
fn use_opaque_pipeline(scene: &ProductScene, options: JobOptions) -> bool {
!scene.has_transmission()
&& !options.volume.is_some_and(|volume| volume.active())
&& scene.meshes.iter().all(|body| body.opacity == 1.0 && body.faces.iter().all(|face| face.opacity == 1.0))
}
fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result<Admission> {
if request.integrator != solidcraft_render::job::Integrator::Raster || request.raytrace.is_some() {
return Err(JobError::new(ErrorCode::InvalidRequest, "GPU path rendering does not accept CPU raytrace options"));
@@ -486,10 +564,7 @@ impl ImageExecutor for Executor {
let a = admission(scene, request, options)?;
let limit = self.context.device.limits().max_storage_buffer_binding_size;
let geometry_bytes = 16 + a.triangles.max(1) * 100 + scene.meshes.iter().map(|m| m.mesh.positions.len() as u64 * 32).sum::<u64>();
let texture_bytes = request
.textures
.as_ref()
.map_or(16, |t| t.summary().linear_pixel_bytes + 4 * (5 + scene.meshes.len() as u64 + t.bindings().len() as u64 * 24));
let texture_bytes = request.textures.as_ref().map_or(16, |t| textures::packed_bytes(t, scene.meshes.len()));
let environment_bytes =
request.environment.as_ref().map_or(48, |source| 16 + u64::from(source.info().width) * u64::from(source.info().height) * 32);
let node_bytes = a.triangles.max(1) * 64;
@@ -542,6 +617,8 @@ struct Task {
context: Arc<Context>,
request: ImageRequest,
options: JobOptions,
opaque_scene: bool,
has_textures: bool,
cancel: CancelToken,
uniform: wgpu::Buffer,
accumulation: wgpu::Buffer,
@@ -571,6 +648,10 @@ struct Task {
}
impl Task {
fn new(context: Arc<Context>, scene: ProductScene, mut request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result<Self> {
cancel.check()?;
let opaque_scene = use_opaque_pipeline(&scene, options);
let has_textures = request.textures.is_some();
context.prepare_scene_pipeline(opaque_scene, has_textures, options.nested_media)?;
cancel.check()?;
let start = Instant::now();
let aging = options.aging.gpu_layers([request.camera.target.x, request.camera.target.y, request.camera.target.z])?;
@@ -655,6 +736,8 @@ impl Task {
cancel.check()?;
Ok(Self {
dispatch_budget: Default::default(),
opaque_scene,
has_textures,
context,
request,
options,
@@ -793,9 +876,10 @@ impl Task {
let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("path tile") });
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("path tile"), timestamp_writes: None });
pass.set_pipeline(&context.pipeline);
let pipeline = context.prepared_scene_pipeline(self.opaque_scene, self.has_textures, self.options.nested_media)?;
pass.set_pipeline(pipeline);
pass.set_bind_group(0, &self.bind, &[]);
pass.dispatch_workgroups(count.div_ceil(64), 1, 1);
pass.dispatch_workgroups(count.div_ceil(PATH_WORKGROUP_SIZE), 1, 1);
}
let submission = context.queue.submit([encoder.finish()]);
checked(scopes)?;
+56 -41
View File
@@ -7,7 +7,7 @@ struct Triangle {
// optics.xyz: extinction per mm, optics.w: body/medium identity (1..16384).
base: vec4<f32>, parameters: vec4<f32>, optics: vec4<f32>,
coat: vec4<f32>, // weight, perceptual roughness, IOR, shadow transmission flag
interior: vec4<f32>, // scattering/mm, HG g, reserved, immediate parent triangle+1
interior: vec4<f32>, // scattering/mm, HG g, flags (stage=1, scalar face=2), immediate parent triangle+1
};
struct Node { lo: vec3<f32>, first: u32, hi: vec3<f32>, count: u32 };
struct AreaLight { center: vec4<f32>, u: vec4<f32>, v: vec4<f32>, radiance: vec4<f32> };
@@ -57,6 +57,8 @@ fn medium_failure(radiance: vec3<f32>, coverage: f32, pixel: u32, bounce: u32, c
}
const PI: f32 = 3.141592653589793;
const FAR: f32 = 1e30;
override OPAQUE_SCENE: bool = false;
override HAS_TEXTURES: bool = false;
// Header: triangle count, vertex offset, material offset, planar-patch offset (all words).
// Indexed triangles contain three vertex indices and one resolved material ID.
@@ -101,7 +103,7 @@ struct Medium { id: f32, ior: f32, sigma: vec3<f32>, scatter: vec2<f32> };
// Establish the complete certified containment stack even when the camera starts
// inside a liquid or a ray starts on an opaque object inside a container. Parent
// references are immutable CPU-certified material references, never AABB guesses.
fn initialize_media(hit_index:u32,d:vec3<f32>,stack:ptr<function,array<Medium,16>>,count:ptr<function,u32>) -> bool {
fn initialize_media(hit_index:u32,d:vec3<f32>,stack:ptr<function,array<Medium,MEDIUM_CAPACITY>>,count:ptr<function,u32>) -> bool {
let first=triangle(hit_index);
if first.base.w<=0.0 || first.parameters.w>=0.0 {return true;}
let outward=unit(cross(first.p1.xyz-first.p0.xyz,first.p2.xyz-first.p0.xyz));
@@ -109,7 +111,7 @@ fn initialize_media(hit_index:u32,d:vec3<f32>,stack:ptr<function,array<Medium,16
var reference=select(hit_index+1u,u32(first.interior.w),entering);
var length=0u;
while reference>0u {
if length>=16u {return false;}
if length>=MEDIUM_CAPACITY {return false;}
let t=triangle(reference-1u);
(*stack)[length]=Medium(t.optics.w,t.parameters.z,t.optics.xyz,t.interior.xy);
reference=u32(t.interior.w);
@@ -833,14 +835,15 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
var coverage = 0.0;
var previous_pdf = 0.0;
var previous_delta = true;
var media: array<Medium,16>;
var media: array<Medium,MEDIUM_CAPACITY>;
var medium_count = 0u;
var texture_path_length = 0.0;
for (var bounce = 0u; bounce < u.sampling.y; bounce += 1u) {
// Closed-glass continuations set an excluded producing triangle; every
// other launch (camera, opaque or thin-sheet surface) does not.
let continued = ray_excluded != 0xffffffffu;
let hit = trace_precise(o,o_low,d,false,ray_excluded,ray_minimum,medium_count>0u);
if u.lighting.w>0.0 && medium_count==0u && hit.triangle!=0xffffffffu {
if !OPAQUE_SCENE && u.lighting.w>0.0 && medium_count==0u && hit.triangle!=0xffffffffu {
if !initialize_media(hit.triangle,d,&media,&medium_count) {return medium_failure(radiance,coverage,pixel,bounce,4u);}
}
if medium_count>0u && media[medium_count-1u].scatter.x>0.0 {
@@ -848,6 +851,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
let boundary=min(hit.distance,emitter_hit_precise(o,o_low,d,ray_minimum).distance);
let travel=-log(1.0-random(&rng))/current.scatter.x;
if travel<boundary {
texture_path_length+=travel;
let position=o+o_low+d*travel;
let traversed=precise_point_delta(position,vec3<f32>(0.0),previous_position,previous_position_low);
throughput*=exp(-current.sigma*length(traversed));
@@ -871,6 +875,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
if length>0.0 {
let travel=-log(1.0-random(&rng))/u.volume_min.w;
if travel<length {
texture_path_length+=segment.x+travel;
let position=o+o_low+d*(segment.x+travel);
coverage=1.0;
throughput*=u.volume_albedo.xyz;
@@ -932,41 +937,37 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
}
coverage = 1.0;
ray_excluded = 0xffffffffu; ray_minimum = u.lighting.x;
var t = triangle(hit.triangle); let v = -d;
var geometric = unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz));
let entering = dot(geometric,v)>=0.0;
if !entering { geometric = -geometric; }
let captured = triangle(hit.triangle); let v = -d;
let outward = unit(cross(captured.p1.xyz-captured.p0.xyz,captured.p2.xyz-captured.p0.xyz));
let entering = dot(outward,v)>=0.0;
let geometric = select(-outward,outward,entering);
var ni = 1.0;
if medium_count > 0u {
let current = media[medium_count-1u];
ni = current.ior;
}
var n = unit(t.n0.xyz*hit.bary.x+t.n1.xyz*hit.bary.y+t.n2.xyz*hit.bary.z);
if dot(n,geometric)<0.0 { n = -n; }
if dot(n,v)<=0.0 { n = geometric; }
// Recover the surface point from barycentrics. A distant ray's f32 distance
// loses precision on skinny triangles; o+d*t can land behind the surface
// and make the next shadow ray intersect the same face.
var position = surface_point(t,hit.bary);
if medium_count > 0u {ni = media[medium_count-1u].ior;}
var position = surface_point(captured,hit.bary);
var position_low = vec3<f32>(0.0);
if t.base.w>0.0 && t.parameters.w<0.0 {
let point=surface_point_precise(t,hit.bary);
position=point.hi; position_low=point.lo;
if captured.base.w>0.0 && captured.parameters.w<0.0 {
let point=surface_point_precise(captured,hit.bary);
position=point.hi;position_low=point.lo;
}
let shading_position = position+position_low;
t = texture_surface(t,shading_position);
t = aged_surface(t,shading_position,unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz)));
let original_normal = n;
n = texture_normal(t,shading_position,n,geometric);
if dot(n,v)<=0.0 { n=original_normal; }
let shading_position=position+position_low;
texture_path_length+=length(precise_point_delta(position,position_low,o,o_low));
if medium_count > 0u {
let segment=precise_point_delta(position,position_low,previous_position,previous_position_low);
throughput *= exp(-media[medium_count-1u].sigma*length(segment));
}
previous_position = position; previous_position_low=position_low;
o = position + geometric*(u.lighting.x*2.0); o_low=vec3<f32>(0.0);
radiance += throughput*direct_light(t,position,o,n,geometric,v,u.sampling.y-bounce-1u,&rng);
if t.base.w > 0.0 && random(&rng) < t.base.w {
// Captured dielectric flags are exactly one, and opaque flags zero.
// Maps are admitted only on opaque bodies; aging also leaves glass
// unchanged. Resolve glass before any sampler temporaries become live.
if !OPAQUE_SCENE && captured.base.w > 0.0 && random(&rng) < captured.base.w {
let t=captured;
let interpolated=unit(captured.n0.xyz*hit.bary.x+captured.n1.xyz*hit.bary.y+captured.n2.xyz*hit.bary.z);
let winding_normal=select(interpolated,-interpolated,dot(interpolated,geometric)<0.0);
let n=select(geometric,winding_normal,dot(winding_normal,v)>0.0);
// The dielectric flag makes every direct-light closure weight zero;
// direct_light consumes no random values on this zero-weight branch.
var optical_normal=n;
var nt = t.parameters.z;
if t.parameters.w < 0.0 && entering && medium_count > 0u && u.lighting.w==0.0 {
return medium_failure(radiance,coverage,pixel,bounce,4u);
@@ -994,14 +995,14 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
nt = 1.0;
if medium_count > 1u { nt = media[medium_count-2u].ior; }
}
var f = dielectric(clamp(dot(n,v),0.0,1.0),ni,nt);
var transmitted = refract(d,n,ni/nt);
var f = dielectric(clamp(dot(optical_normal,v),0.0,1.0),ni,nt);
var transmitted = refract(d,optical_normal,ni/nt);
// A bent shading normal must not send a transmitted ray into the wrong
// geometric hemisphere. Fall back to the geometric interface there.
if (f.z >= 0.0 && dot(transmitted,geometric) >= 0.0) || dot(reflect(d,n),geometric) <= 0.0 {
n = geometric;
f = dielectric(clamp(dot(n,v),0.0,1.0),ni,nt);
transmitted = refract(d,n,ni/nt);
if (f.z >= 0.0 && dot(transmitted,geometric) >= 0.0) || dot(reflect(d,optical_normal),geometric) <= 0.0 {
optical_normal = geometric;
f = dielectric(clamp(dot(optical_normal,v),0.0,1.0),ni,nt);
transmitted = refract(d,optical_normal,ni/nt);
}
// The first Fresnel choice is stratified conditionally on the same
// primary/prefix path. Each stratum is weighted equally; later random
@@ -1021,7 +1022,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
if branch < probability {
previous_delta=true; previous_scatter_position=position; previous_scatter_position_low=position_low; suppress_direct=false;
throughput *= weights.reflection/probability;
d = reflect(d,n);
d = reflect(d,optical_normal);
} else {
throughput *= weights.transmission/(1.0-probability);
if t.coat.w>0.0 { previous_pdf*=1.0-probability; }
@@ -1033,13 +1034,13 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
}
} else if branch < (f.x+f.y)*0.5 {
previous_delta=true; previous_scatter_position=position; previous_scatter_position_low=position_low; suppress_direct=false;
d = reflect(d,n);
d = reflect(d,optical_normal);
} else {
if t.coat.w>0.0 { suppress_direct=suppress_direct || !previous_delta; }
else { suppress_direct=false; }
previous_delta=true; previous_scatter_position=position; previous_scatter_position_low=position_low;
if entering {
if medium_count >= 16u { return medium_failure(radiance,coverage,pixel,bounce,4u); }
if medium_count >= MEDIUM_CAPACITY { return medium_failure(radiance,coverage,pixel,bounce,4u); }
media[medium_count] = Medium(t.optics.w,nt,t.optics.xyz,t.interior.xy);
medium_count += 1u;
} else { medium_count -= 1u; }
@@ -1063,6 +1064,18 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
}
continue;
}
let map_record=texture_record(captured.optics.w);
let gradients=texture_gradients(map_record,geometric,d,hit.distance,texture_path_length,bounce);
let mapped_surface=texture_surface(map_record,captured.base.xyz,captured.parameters.x,captured.parameters.y,shading_position,gradients,(u32(captured.interior.z)&2u)!=0u);
// Retain immutable geometry and medium data across optical map evaluation.
let textured=Triangle(captured.p0,captured.p1,captured.p2,captured.n0,captured.n1,captured.n2,vec4<f32>(mapped_surface.color,captured.base.w),vec4<f32>(mapped_surface.metallic,mapped_surface.roughness,captured.parameters.zw),captured.optics,captured.coat,captured.interior);
let t=aged_surface(textured,shading_position,outward);
let interpolated=unit(captured.n0.xyz*hit.bary.x+captured.n1.xyz*hit.bary.y+captured.n2.xyz*hit.bary.z);
let winding_normal=select(interpolated,-interpolated,dot(interpolated,geometric)<0.0);
let original_normal=select(geometric,winding_normal,dot(winding_normal,v)>0.0);
let mapped_normal=texture_normal(map_record,mapped_surface.normal,original_normal,geometric);
let n=select(original_normal,mapped_normal,dot(mapped_normal,v)>0.0);
radiance += throughput*direct_light(t,position,o,n,geometric,v,u.sampling.y-bounce-1u,&rng);
d = sample_surface(t,n,v,&rng);
let nl = dot(n,d);
if nl<=0.0 || dot(geometric,d)<=0.0 { break; }
@@ -1106,7 +1119,7 @@ fn adaptive_target(mean: vec4<f32>, m2: vec4<f32>) -> u32 {
return clamp(u32(max(max(need.x,need.y),max(need.z,need.w))),u.adaptive_budget.y,maximum);
}
@compute @workgroup_size(64)
@compute @workgroup_size(32)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let pixel = u.image.w + gid.x;
let pixels = u.image.x*u.image.y;
@@ -1168,6 +1181,8 @@ fn camera_reference() {
// Bias signed test coordinates for the radiance readback's nonnegative contract.
accumulation[0] = vec4<f32>(ray.origin+vec3<f32>(16.0),1.0);
accumulation[1] = vec4<f32>(ray.direction+vec3<f32>(2.0),1.0);
accumulation[2] = vec4<f32>(texture_camera_direction_delta(ray.direction,2.0*u.right.xyz/f32(u.image.x))+vec3<f32>(16.0),1.0);
accumulation[3] = vec4<f32>(texture_camera_direction_delta(ray.direction,-2.0*u.up.xyz/f32(u.image.y))+vec3<f32>(16.0),1.0);
}
// Deterministic image-space ball-lens check. Uses the production BVH/intersection
+1
View File
@@ -123,6 +123,7 @@ mod tests {
surface: OpaqueSurface::new(Vec3::ZERO, 0.0, 0.5, 1.5).unwrap(),
transmission: None,
medium: body,
scalar_face: false,
}
}
+11 -6
View File
@@ -18,6 +18,7 @@ pub(super) struct Triangle {
pub surface: OpaqueSurface,
pub transmission: Option<Transmission>,
pub medium: u32,
pub scalar_face: bool,
}
type MediumEdge = (usize, usize, i32);
pub(super) fn medium_preparation_bytes(scene: &ProductScene) -> u64 {
@@ -156,7 +157,14 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
if transmission.is_some() && surface.metallic() != 0.0 {
return Err(invalid("transmission requires a nonmetallic surface"));
}
triangles.push(Triangle { p, indices: global_indices, surface, transmission, medium: body_index as u32 + 1 });
triangles.push(Triangle {
p,
indices: global_indices,
surface,
transmission,
medium: body_index as u32 + 1,
scalar_face: look.is_some(),
});
}
validate_medium(&triangles[body_start..], cancel)?;
let body_triangles = &triangles[body_start..];
@@ -235,11 +243,8 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
Vec3::new(
scatter.map_or(0.0, |s| s.scattering_per_mm),
scatter.map_or(0.0, |s| s.anisotropy),
if scene.meshes.get(t.medium.saturating_sub(1) as usize).is_some_and(|body| body.name.starts_with("__render_stage__/")) {
1.0
} else {
0.0
},
(u32::from(scene.meshes.get(t.medium.saturating_sub(1) as usize).is_some_and(|body| body.name.starts_with("__render_stage__/")))
| (u32::from(t.scalar_face) << 1)) as f64,
),
parent_triangle as f32,
);
+1
View File
@@ -16,6 +16,7 @@ fn decades(count: usize) -> Vec<Triangle> {
surface,
transmission: None,
medium: 0,
scalar_face: false,
}
})
.collect()
+1
View File
@@ -33,6 +33,7 @@ fn shadow_transmittance(origin: vec3<f32>, direction: vec3<f32>, limit: f32) ->
return result;
}
if step==64u { return blocked_shadow(); }
if OPAQUE_SCENE {return blocked_shadow();}
let t = triangle(hit.triangle);
if t.base.w<=0.0 || t.coat.w<=0.0 { return blocked_shadow(); }
var position=surface_point(t,hit.bary);
+623 -10
View File
@@ -308,9 +308,9 @@ fn gpu_thin_lens_focus_and_defocus_match_geometric_oracle() {
compilation_options: Default::default(),
cache: None,
});
for (yaw, pitch, roll) in [(0.0, 0.0, 0.0), (-0.45, 0.5, 0.7)] {
for (yaw, pitch, roll, fov) in [(0.0, 0.0, 0.0, 0.7), (-0.45, 0.5, 0.7, 0.7), (-0.45, 0.5, 0.7, 2.0)] {
let mut request = request(2);
request.camera = Camera { distance: 12.0, fov: 0.7, yaw, pitch, roll, ..Default::default() };
request.camera = Camera { distance: 12.0, fov, yaw, pitch, roll, ..Default::default() };
let camera = request.camera;
let lens = solidcraft_render::job::ThinLens { aperture_radius_mm: 0.4, focus_distance_mm: 9.0 };
let options = JobOptions { lens: Some(lens), ..Default::default() };
@@ -340,6 +340,20 @@ fn gpu_thin_lens_focus_and_defocus_match_geometric_oracle() {
let direction = vec(rays[1]) - Vec3::new(2.0, 2.0, 2.0);
let disk = (right * (azimuth * std::f64::consts::TAU).cos() + up * (azimuth * std::f64::consts::TAU).sin())
* (radial.sqrt() * lens.aperture_radius_mm);
// Differentiate independently constructed f64 rays with the lens
// point fixed; the production helper keeps no camera live state.
let direction_at = |x: f64, y: f64| {
((right * x + up * y) * (camera.half_height() * lens.focus_distance_mm / camera.distance) - back * lens.focus_distance_mm - disk)
.normalized()
.unwrap()
};
let h = 1e-3;
for (slot, dx, dy) in [(2, h, 0.), (3, 0., -h)] {
// request(2) makes one pixel exactly one unit of normalized UV.
let expected = (direction_at(ux + dx, uy + dy) - direction_at(ux - dx, uy - dy)) / (2.0 * h);
let actual = vec(rays[slot]) - Vec3::new(16., 16., 16.);
assert!((actual - expected).len() < 4e-6, "fov={fov},uv=({ux},{uy}),slot={slot}: {actual:?} vs {expected:?}");
}
assert!((origin - eye - disk).len() < 3e-6);
let focus_hit = origin + direction * ((focal - origin).dot(back) / direction.dot(back));
assert!((focus_hit - focal).len() < 5e-6, "focus {focus_hit:?} != {focal:?}");
@@ -525,11 +539,14 @@ fn gpu_solid_and_thin_slabs_match_absorbing_interreflection_oracle() {
#[test]
fn shader_validates_without_a_device() {
let module = naga::front::wgsl::parse_str(SHADER).unwrap();
let parameters = module.types.iter().find(|(_, ty)| ty.name.as_deref() == Some("Params")).unwrap().1;
let naga::TypeInner::Struct { span, .. } = &parameters.inner else { panic!("Params must be a struct") };
assert_eq!(*span as usize, PARAMETER_BYTES);
naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap();
for source in [SHADER, SINGLE_MEDIUM_SHADER] {
let module = naga::front::wgsl::parse_str(source).unwrap();
let parameters = module.types.iter().find(|(_, ty)| ty.name.as_deref() == Some("Params")).unwrap().1;
let naga::TypeInner::Struct { span, .. } = &parameters.inner else { panic!("Params must be a struct") };
assert_eq!(*span as usize, PARAMETER_BYTES);
naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap();
assert_eq!(module.entry_points.iter().find(|entry| entry.name == "main").unwrap().workgroup_size, [PATH_WORKGROUP_SIZE, 1, 1]);
}
}
/// #6705: native compilers inline every call. With 33 inlined BVH walks in `main` (three path
@@ -1852,6 +1869,13 @@ fn gpu_hdr_and_sun_shadow_mis_preserve_index_matched_energy() {
}
fn texture_fixture(frame: solidcraft_render::job::textures::PlanarFrame) -> Arc<solidcraft_render::job::textures::RuntimeTextures> {
texture_fixture_filtering(frame, false)
}
fn texture_fixture_filtering(
frame: solidcraft_render::job::textures::PlanarFrame,
portable: bool,
) -> Arc<solidcraft_render::job::textures::RuntimeTextures> {
use image::ImageEncoder;
use solidcraft_render::{
job::textures::{RuntimeTextures, TextureBinding, TextureMap},
@@ -1860,7 +1884,7 @@ fn texture_fixture(frame: solidcraft_render::job::textures::PlanarFrame) -> Arc<
let map = |pixels: &[u8], role| {
let mut bytes = Vec::new();
image::codecs::png::PngEncoder::new(&mut bytes).write_image(pixels, 2, 2, image::ExtendedColorType::Rgba8).unwrap();
TextureMap::new(bytes, role).unwrap()
if portable { TextureMap::new_portable(bytes, role).unwrap() } else { TextureMap::new(bytes, role).unwrap() }
};
Arc::new(
RuntimeTextures::new(vec![TextureBinding {
@@ -1899,6 +1923,77 @@ fn texture_admission_rejects_glass_and_stale_identity_and_honors_cancellation()
assert!(admission(&scene, &input, JobOptions::default()).is_err());
}
#[test]
fn host_readiness_includes_unmapped_non_nested_glass() {
let Some(executor) = executor() else { return };
let context = &executor.context;
assert!(context.prepared_scene_pipeline(true, false, false).is_ok());
assert!(context.prepared_scene_pipeline(false, false, false).is_ok(), "a ready host must already prepare ordinary unmapped glass");
let plain = scene_pipeline_variant(false, false, false).unwrap();
assert!(context.scene_pipelines[plain].get().is_some());
for (opaque, maps, nested) in [(true, true, false), (false, false, true), (false, true, false), (false, true, true)] {
let variant = scene_pipeline_variant(opaque, maps, nested).unwrap();
assert!(context.scene_pipelines[variant].get().is_none(), "uncommon map/nesting programs stay lazy");
}
let mut glass = sphere(white());
glass.meshes[0].transmission = Some(clear_glass());
let options = JobOptions { samples: 1, max_depth: 3, ..Default::default() };
let mut task = Task::new(context.clone(), glass, request(2), options, CancelToken::default()).unwrap();
assert!(!task.opaque_scene && !task.has_textures);
task.complete_sample().unwrap();
let pixels = task.read_linear().unwrap();
assert_eq!(pixels.len(), 4);
assert!(pixels.iter().flatten().all(|value| value.is_finite()));
}
#[test]
fn opaque_scene_specialization_preserves_body_face_and_volume_media() {
let mut variants = std::collections::BTreeSet::new();
for opaque in [false, true] {
for maps in [false, true] {
for nested in [false, true] {
let slot = scene_pipeline_variant(opaque, maps, nested);
assert_eq!(slot.is_none(), opaque && !maps, "only opaque/no-map uses the eager base");
assert!(slot.is_none_or(|index| index < SCENE_PIPELINE_CACHE_SLOTS));
variants.insert(slot);
}
if opaque {
assert_eq!(scene_pipeline_variant(opaque, maps, false), scene_pipeline_variant(opaque, maps, true));
} else {
assert_ne!(
scene_pipeline_variant(opaque, maps, false),
scene_pipeline_variant(opaque, maps, true),
"single and nested medium stacks require distinct programs"
);
}
}
}
assert_eq!(variants.len(), SCENE_PIPELINE_CACHE_SLOTS + 1);
let mut scene = sphere(white());
let options = JobOptions::default();
assert!(use_opaque_pipeline(&scene, options));
scene.meshes[0].transmission = Some(clear_glass());
assert!(!use_opaque_pipeline(&scene, options));
scene.meshes[0].transmission = None;
scene.meshes[0].faces.push(solidcraft_render::FaceAppearance {
face: 0,
color: [255; 3],
opacity: 1.0,
surface: Some(white()),
transmission: Some(clear_glass()),
});
assert!(!use_opaque_pipeline(&scene, options));
scene.meshes[0].faces[0].transmission = None;
assert!(use_opaque_pipeline(&scene, options));
scene.meshes[0].faces[0].opacity = 0.5;
assert!(!use_opaque_pipeline(&scene, options));
scene.meshes[0].faces.clear();
assert!(!use_opaque_pipeline(&scene, JobOptions { volume: Some(Default::default()), ..options }));
assert!(use_opaque_pipeline(
&scene,
JobOptions { volume: Some(solidcraft_render::job::volume::HomogeneousVolume { extinction_per_mm: 0.0, ..Default::default() }), ..options }
));
}
#[test]
fn gpu_planar_color_and_normal_maps_match_cpu_sampling_oracle() {
use solidcraft_render::job::textures::{PlanarFrame, sample_map};
let Some(executor) = executor() else { return };
@@ -1914,7 +2009,7 @@ fn gpu_planar_color_and_normal_maps_match_cpu_sampling_oracle() {
layout: Some(&layout),
module: &shader,
entry_point: Some("texture_reference"),
compilation_options: Default::default(),
compilation_options: wgpu::PipelineCompilationOptions { constants: &[("HAS_TEXTURES", 1.0)], ..Default::default() },
cache: None,
});
for handed in [1., -1.] {
@@ -2928,6 +3023,517 @@ fn identical_maps_pack_once_for_multiple_gpu_bodies() {
assert_ne!(a, b, "bindings keep separate coordinate records");
assert_eq!(word(a + 3), word(b + 3), "one color payload");
assert_eq!(word(a + 12), word(b + 12), "one normal payload");
assert_eq!(textures::packed_bytes(&input, 2), bytes.len() as u64, "admission does not charge unused mip tails or duplicate legacy maps");
}
#[test]
fn packed_legacy_and_portable_gpu_maps_keep_distinct_policies_in_both_orders() {
use image::ImageEncoder;
use solidcraft_render::{
job::textures::{PlanarFrame, RuntimeTextures, TextureMap},
texture_input::MapRole,
};
let mut encoded = Vec::new();
image::codecs::png::PngEncoder::new(&mut encoded).write_image(&[128, 64, 32, 255].repeat(15), 5, 3, image::ExtendedColorType::Rgba8).unwrap();
let legacy = TextureMap::new(encoded.clone(), MapRole::BaseColor).unwrap();
let portable = TextureMap::new_portable(encoded, MapRole::BaseColor).unwrap();
let original = texture_fixture(PlanarFrame { origin: [0.; 3], u: [1., 0., 0.], v: [0., 1., 0.] });
for maps in [[legacy.clone(), portable.clone()], [portable.clone(), legacy.clone()]] {
let bindings = maps
.iter()
.enumerate()
.map(|(index, map)| {
let mut binding = original.bindings()[0].clone();
binding.body_index = index;
binding.body_name = format!("Policy {index}");
binding.base_color = Some(map.clone());
binding.normal = None;
binding
})
.collect();
let input = RuntimeTextures::new(bindings).unwrap();
let bytes = textures::flatten(Some(&input), 2, Vec3::ZERO, &CancelToken::default()).unwrap();
let word = |i: usize| u32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().unwrap()) as usize;
let descriptors = [word(word(5) + 3), word(word(6) + 3)];
assert_ne!(descriptors[0], descriptors[1], "same bytes and role retain separate filtering policies");
// Header + two body records, then exactly one legacy base and one 5x3 -> 2x1 -> 1x1 chain.
assert_eq!(bytes.len(), 8 * 4 + 2 * 24 * 4 + (8 * 4 + 15 * 16) + (16 * 4 + 18 * 16));
assert_eq!(textures::packed_bytes(&input, 2), bytes.len() as u64);
for (descriptor, map) in descriptors.into_iter().zip(maps) {
assert_eq!(word(descriptor), if map.gpu_mip_filtering() { 3 } else { 1 });
assert_eq!(word(descriptor + 2), usize::from(map.gpu_mip_filtering()));
let base = word(descriptor + 4) * 4;
let expected: Vec<_> = map.decode(&CancelToken::default()).unwrap().iter().flat_map(|value| value.to_le_bytes()).collect();
assert_eq!(&bytes[base..base + expected.len()], expected, "level-zero encoded-role interpretation stays exact");
}
}
}
#[test]
fn packed_gpu_mips_preserve_odd_size_linear_color_and_data_means() {
use image::ImageEncoder;
use solidcraft_render::{
job::textures::{PlanarFrame, RuntimeTextures, TextureMap},
texture_input::MapRole,
};
let mut encoded = Vec::new();
let pixels: Vec<u8> = (0..15).flat_map(|i| [if i & 1 == 0 { 64 } else { 192 }, 128, 255, 0]).collect();
image::codecs::png::PngEncoder::new(&mut encoded).write_image(&pixels, 5, 3, image::ExtendedColorType::Rgba8).unwrap();
let original = texture_fixture(PlanarFrame { origin: [0.; 3], u: [1., 0., 0.], v: [0., 1., 0.] });
let mut binding = original.bindings()[0].clone();
binding.base_color = Some(TextureMap::new_portable(encoded.clone(), MapRole::BaseColor).unwrap());
binding.normal = None;
binding.roughness = Some(TextureMap::new_portable(encoded, MapRole::Roughness).unwrap());
let input = RuntimeTextures::new(vec![binding]).unwrap();
let bytes = textures::flatten(Some(&input), 1, Vec3::ZERO, &CancelToken::default()).unwrap();
let word = |i: usize| u32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().unwrap()) as usize;
let record = word(5);
let color = word(record + 3);
let data = word(record + 16);
assert_ne!(color, data, "the same encoded source retains distinct role interpretation");
for (descriptor, linear) in [(color, true), (data, false)] {
assert_eq!(word(descriptor), 3, "5x3 -> 2x1 -> 1x1");
let last = descriptor + 4 + 2 * 4;
assert_eq!((word(last + 1), word(last + 2)), (1, 1));
let expected = (0..15)
.map(|i| {
let value = if i & 1 == 0 { 64 } else { 192 };
if linear { solidcraft_render::surface::srgb8_to_linear(value) } else { f64::from(value) / 255. }
})
.sum::<f64>()
/ 15.;
let actual = f32::from_le_bytes(bytes[word(last) * 4..word(last) * 4 + 4].try_into().unwrap());
assert!((f64::from(actual) - expected).abs() < 1e-7, "{actual} vs {expected}");
}
assert!((bytes.capacity() as u64) < input.working_bytes(), "the admitted preparation includes the full packed chain capacity");
}
#[test]
fn gpu_trilinear_minification_matches_singular_value_lod_and_repeat_oracle() {
use solidcraft_render::{
job::textures::PlanarFrame,
texture_lod::select_isotropic_lod,
texture_sampling::{
TextureView,
mips::{MAX_MIP_TAIL_BYTES, MipChain},
},
};
let Some(executor) = executor() else { return };
let context = &executor.context;
let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&context.layout)],
immediate_size: 0,
});
let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: Some(&layout),
module: &shader,
entry_point: Some("texture_mip_reference"),
compilation_options: wgpu::PipelineCompilationOptions { constants: &[("HAS_TEXTURES", 1.0)], ..Default::default() },
cache: None,
});
let frame = PlanarFrame { origin: [0.; 3], u: [2., 0., 0.], v: [0., 2., 0.] };
let source = texture_fixture_filtering(frame, true);
let pixels = source.bindings()[0].base_color.as_ref().unwrap().decode(&CancelToken::default()).unwrap();
let base = TextureView::new(&pixels, [2, 2]).unwrap();
let chain = MipChain::prepare(base, MAX_MIP_TAIL_BYTES, || false).unwrap();
for portable in [true, false] {
let source = texture_fixture_filtering(frame, portable);
for (point, dx, dy) in [
(Vec3::new(0.5, 0.5, 0.), [0., 0.], [0., 0.]),
(Vec3::new(-0.01, 0.125, 0.), [0.75, 0.], [0., 0.25]),
(Vec3::new(0.01, 0.125, 0.), [0.75, 0.], [0., 0.25]),
(Vec3::new(-0.25, 1.125, 0.), [0.4, -0.5], [0.5, 0.25]),
(Vec3::new(0., 0., 0.), [4., 0.], [0., 4.]),
// Legacy sampling must bypass LOD arithmetic even when a finite gradient
// would overflow its texel-space multiplication. This is not a portable-footprint case.
(Vec3::new(0.5, 0.5, 0.), [3e38, 0.], [0., 3e38]),
] {
let extreme = dx[0] > 1e30;
if portable && extreme {
continue;
}
let mut input = request(2);
input.textures = Some(source.clone());
let mut task = Task::new(context.clone(), sphere(white()), input, JobOptions::default(), CancelToken::default()).unwrap();
let mut params = vec![0; 32];
scene::vector(&mut params, point, 0.);
scene::vector(&mut params, Vec3::new(dx[0], dx[1], 0.), 0.);
scene::vector(&mut params, Vec3::new(dy[0], dy[1], 0.), 0.);
scene::vector(&mut params, Vec3::Z, 0.);
context.queue.write_buffer(&task.uniform, 0, &params);
let mut encoder = context.device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &task.bind, &[]);
pass.dispatch_workgroups(1, 1, 1);
}
context.queue.submit([encoder.finish()]);
task.sample = 1;
let actual = task.read_linear().unwrap();
let lod = if portable { select_isotropic_lod([2, 2], dx, dy).unwrap().lod } else { 0. };
let expected = if portable {
chain.sample_repeat_lod_opaque(frame.uv(point).unwrap(), lod).unwrap()
} else {
base.sample_repeat_opaque(frame.uv(point).unwrap()).unwrap()
};
assert!((f64::from(actual[1][0]) - lod).abs() < 1e-6, "GPU LOD {actual:?} vs {lod}");
for (a, b) in actual[0].iter().zip(expected) {
assert!((f64::from(*a) - b).abs() < 2e-6, "GPU portable={portable} {actual:?} vs {expected:?}");
}
}
}
}
#[test]
fn gpu_scalar_faces_preserve_legacy_roles_and_suppress_only_portable_roles() {
use image::ImageEncoder;
use solidcraft_render::{
FaceAppearance,
job::textures::{PlanarFrame, RuntimeTextures, TextureMap, sample_map},
texture_input::MapRole,
};
let Some(executor) = executor() else { return };
let context = &executor.context;
let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&context.layout)],
immediate_size: 0,
});
let pipeline = |entry_point| {
context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: Some(&layout),
module: &shader,
entry_point: Some(entry_point),
compilation_options: wgpu::PipelineCompilationOptions { constants: &[("HAS_TEXTURES", 1.0)], ..Default::default() },
cache: None,
})
};
let color_normal_pipeline = pipeline("texture_reference");
let scalar_pipeline = pipeline("texture_scalar_reference");
let frame = PlanarFrame { origin: [0.; 3], u: [2., 0., 0.], v: [0., 2., 0.] };
let point = Vec3::new(-0.25, 1.125, 0.);
let uv = frame.uv(point).unwrap();
let scalar = |value, role, portable| {
let mut bytes = Vec::new();
image::codecs::png::PngEncoder::new(&mut bytes).write_image(&[value, value, value, 255], 1, 1, image::ExtendedColorType::Rgba8).unwrap();
if portable { TextureMap::new_portable(bytes, role).unwrap() } else { TextureMap::new(bytes, role).unwrap() }
};
for color_portable in [false, true] {
for normal_portable in [false, true] {
let fixture = texture_fixture_filtering(frame, color_portable);
let normal_fixture = texture_fixture_filtering(frame, normal_portable);
let mut binding = fixture.bindings()[0].clone();
binding.normal = normal_fixture.bindings()[0].normal.clone();
binding.roughness = Some(scalar(192, MapRole::Roughness, color_portable));
binding.metallic = Some(scalar(64, MapRole::Metallic, normal_portable));
let color = sample_map(&binding.base_color.as_ref().unwrap().decode(&CancelToken::default()).unwrap(), [2, 2], uv).unwrap();
let normal = sample_map(&binding.normal.as_ref().unwrap().decode(&CancelToken::default()).unwrap(), [2, 2], uv).unwrap();
let mut input = request(2);
input.textures = Some(Arc::new(RuntimeTextures::new(vec![binding]).unwrap()));
let face_color = Vec3::new(0.2, 0.4, 0.6);
let face = OpaqueSurface::new(face_color, 0.3, 0.2, 1.7).unwrap();
let mut scene = sphere(white());
scene.meshes[0].faces.push(FaceAppearance { face: 0, color: [255; 3], opacity: 1., surface: Some(face), transmission: None });
let mut task = Task::new(context.clone(), scene, input, JobOptions::default(), CancelToken::default()).unwrap();
let mut params = vec![0; 32];
scene::vector(&mut params, point, 0.);
scene::vector(&mut params, Vec3::ZERO, 0.);
scene::vector(&mut params, Vec3::Z, 0.);
scene::vector(&mut params, Vec3::Z, 0.);
context.queue.write_buffer(&task.uniform, 0, &params);
let run = |task: &mut Task, pipeline: &wgpu::ComputePipeline| {
let mut encoder = context.device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(pipeline);
pass.set_bind_group(0, &task.bind, &[]);
pass.dispatch_workgroups(1, 1, 1);
}
context.queue.submit([encoder.finish()]);
task.sample = 1;
task.read_linear().unwrap()
};
let actual = run(&mut task, &color_normal_pipeline);
let expected = [face_color.x, face_color.y, face_color.z];
for (channel, value) in expected.into_iter().enumerate() {
let expected = if color_portable { value } else { value * color[channel] };
assert!((f64::from(actual[0][channel]) - expected).abs() < 2e-6, "mixed face color {color_portable}/{normal_portable}: {actual:?}");
}
let expected = if normal_portable { Vec3::Z } else { frame.mapped_normal(Vec3::Z, Vec3::Z, normal, 0.75).unwrap() };
for (actual, expected) in actual[1].iter().zip([expected.x + 2., expected.y + 2., expected.z + 2.]) {
assert!((f64::from(*actual) - expected).abs() < 3e-6, "mixed face normal {color_portable}/{normal_portable}");
}
let actual = run(&mut task, &scalar_pipeline);
let expected = [if normal_portable { 0.3 } else { 64. / 255. }, if color_portable { 0.2 } else { 192. / 255. }, 1.7];
for (actual, expected) in actual[0].iter().zip(expected) {
assert!((f64::from(*actual) - expected).abs() < 2e-6, "mixed face scalars {color_portable}/{normal_portable}");
}
}
}
}
#[test]
fn gpu_wood_minification_converges_to_mean_and_preserves_scalar_face_override() {
use image::ImageEncoder;
use solidcraft_render::{
FaceAppearance,
job::textures::{BaseColorMode, PlanarFrame, RuntimeTextures, TextureBinding, TextureMap},
texture_input::MapRole,
};
let Some(executor) = executor() else { return };
// Reuse the established closed slab fixture as an opaque wooden plank.
let mut scene = glass_slab(false);
scene.meshes[0].name = "wood diagnostic".into();
scene.meshes[0].surface = Some(white());
scene.meshes[0].transmission = None;
let mesh = Arc::make_mut(&mut scene.meshes[0].mesh);
for position in &mut mesh.positions {
position.z -= 0.5;
}
mesh.tri_face = (0..mesh.triangles.len() as u32).collect();
scene.bounds = mesh.bounds();
let pixels: Vec<u8> = (0..64)
.flat_map(|i| {
let v = if i & 1 == 0 { 0 } else { 255 };
[v, v, v, 255]
})
.collect();
let mut encoded = Vec::new();
image::codecs::png::PngEncoder::new(&mut encoded).write_image(&pixels, 8, 8, image::ExtendedColorType::Rgba8).unwrap();
let map = TextureMap::new_portable(encoded, MapRole::BaseColor).unwrap();
let binding = |repeat| TextureBinding {
body_index: 0,
body_name: "wood diagnostic".into(),
frame: PlanarFrame { origin: [0.; 3], u: [repeat, 0., 0.], v: [0., repeat, 0.] },
normal_strength: 1.,
base_color: Some(map.clone()),
normal: None,
roughness: None,
metallic: None,
base_color_mode: BaseColorMode::Replace,
flip_v: false,
};
let render = |scene: ProductScene, source: Option<TextureBinding>, fov: f64, pitch: f64, lens: bool| {
let mut image = request(16);
image.camera.fov = fov;
image.camera.pitch = pitch;
image.textures = source.map(|b| Arc::new(RuntimeTextures::new(vec![b]).unwrap()));
let options = JobOptions {
samples: 1,
max_depth: 1,
lens: lens.then_some(solidcraft_render::job::ThinLens { aperture_radius_mm: 0.15, focus_distance_mm: 4.0 }),
..Default::default()
};
let mut task = Task::new(executor.context.clone(), scene, image, options, CancelToken::default()).unwrap();
task.complete_sample().unwrap();
let pixels = task.read_linear().unwrap();
assert!(pixels.iter().all(|pixel| pixel[3] == 1.0), "the plank must fill every output pixel");
pixels
};
let mut flat = scene.clone();
flat.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0., 1., 1.).unwrap());
for (fov, pitch, lens) in [(0., std::f64::consts::FRAC_PI_2, false), (0.7, 0.65, false), (0.7, 0.65, true)] {
let expected = render(flat.clone(), None, fov, pitch, lens);
let minified = render(scene.clone(), Some(binding(0.25)), fov, pitch, lens);
for (pixel, (actual, expected)) in minified.iter().zip(&expected).enumerate() {
for (a, b) in actual.iter().take(3).zip(expected) {
assert!((a - b).abs() < 2e-5, "pixel={pixel}, fov={fov}, pitch={pitch},lens={lens}: minified {actual:?} vs {expected:?}");
}
}
}
let close = render(scene.clone(), Some(binding(4.)), 0., std::f64::consts::FRAC_PI_2, false);
let spread = close.iter().map(|p| p[0]).fold(f32::NEG_INFINITY, f32::max) - close.iter().map(|p| p[0]).fold(f32::INFINITY, f32::min);
assert!(spread > 0.1, "magnified grain must retain contrast: {spread}");
let mut overridden = scene;
overridden.meshes[0].faces = vec![FaceAppearance {
face: 0,
color: [64, 128, 192],
opacity: 1.,
surface: Some(OpaqueSurface::new(Vec3::new(0.1, 0.2, 0.3), 0., 1., 1.).unwrap()),
transmission: None,
}];
let scalar = render(overridden.clone(), None, 0., std::f64::consts::FRAC_PI_2, false);
let mapped = render(overridden, Some(binding(0.25)), 0., std::f64::consts::FRAC_PI_2, false);
let explicit: Vec<_> = scalar.iter().zip(&mapped).filter(|(a, _)| a[2] > a[0] * 2.).collect();
assert!(explicit.len() > 32, "the diagnostic must cover explicit face pixels");
for (a, b) in explicit {
assert_eq!(a, b, "a scalar face suppresses inherited maps");
}
}
#[test]
fn gpu_mapped_wood_preserves_index_matched_sheet_and_solid_transport() {
use image::ImageEncoder;
use solidcraft_render::{
job::textures::{BaseColorMode, PlanarFrame, RuntimeTextures, TextureBinding, TextureMap},
texture_input::MapRole,
};
let Some(executor) = executor() else { return };
let mut board = glass_slab(false).meshes.remove(0);
board.name = "mixed wood board".into();
board.surface = Some(white());
board.transmission = None;
for position in &mut Arc::make_mut(&mut board.mesh).positions {
position.z -= 0.5;
}
let pixels: Vec<u8> = (0..64)
.flat_map(|i| {
let c = if i & 1 == 0 { 0 } else { 255 };
[c, c, c, 255]
})
.collect();
let mut encoded = Vec::new();
image::codecs::png::PngEncoder::new(&mut encoded).write_image(&pixels, 8, 8, image::ExtendedColorType::Rgba8).unwrap();
let resources = Arc::new(
RuntimeTextures::new(vec![TextureBinding {
body_index: 0,
body_name: board.name.clone(),
frame: PlanarFrame { origin: [0.; 3], u: [0.25, 0., 0.], v: [0., 0.25, 0.] },
normal_strength: 1.,
base_color: Some(TextureMap::new_portable(encoded, MapRole::BaseColor).unwrap()),
normal: None,
roughness: None,
metallic: None,
base_color_mode: BaseColorMode::Replace,
flip_v: false,
}])
.unwrap(),
);
// At IOR1, zero extinction and no scatter, either glass boundary is the
// exact identity. The mean map reflectance .5 receives three fixed lights.
let expected = 0.5 * (3.0 * 0.8 + 1.0 * 0.6 + 1.5 * 0.8) / std::f64::consts::PI;
for mapped in [false, true] {
for thin in [true, false] {
let mut glass = glass_slab(thin).meshes.remove(0);
glass.name = "index matched glazing".into();
for position in &mut Arc::make_mut(&mut glass.mesh).positions {
position.z += 1.0;
}
glass.surface = Some(OpaqueSurface::new(Vec3::ZERO, 0., 1., 1.).unwrap());
glass.transmission =
Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, thin.then_some(0.)).unwrap().with_shadow_transmission(true));
let mut scene = ProductScene { bounds: board.mesh.bounds().union(&glass.mesh.bounds()), meshes: vec![board.clone(), glass] };
if !mapped {
scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0., 1., 1.).unwrap());
}
let mut image = request(16);
image.textures = mapped.then(|| resources.clone());
let mut task = Task::new(
executor.context.clone(),
scene,
image,
JobOptions { samples: 1, max_depth: if thin { 2 } else { 3 }, ..Default::default() },
CancelToken::default(),
)
.unwrap();
assert!(!task.opaque_scene);
assert_eq!(task.has_textures, mapped);
task.complete_sample().unwrap_or_else(|error| panic!("thin={thin},mapped={mapped}: {error:?}"));
for (pixel, value) in task.read_linear().unwrap_or_else(|error| panic!("thin={thin},mapped={mapped}: {error:?}")).iter().enumerate() {
assert_eq!(value[3], 1.0, "thin={thin},mapped={mapped},pixel={pixel}");
for actual in value.iter().take(3) {
assert!((f64::from(*actual) - expected).abs() < 2e-5, "thin={thin},mapped={mapped},pixel={pixel}: {value:?} vs {expected}");
}
}
}
}
}
#[test]
fn gpu_mapped_wood_keeps_fine_detail_behind_large_index_matched_solid_glass() {
use image::ImageEncoder;
use solidcraft_render::{
job::textures::{BaseColorMode, PlanarFrame, RuntimeTextures, TextureBinding, TextureMap},
texture_input::MapRole,
};
let Some(executor) = executor() else { return };
let mut board = glass_slab(false).meshes.remove(0);
board.name = "fine wood diagnostic".into();
board.surface = Some(white());
board.transmission = None;
for position in &mut Arc::make_mut(&mut board.mesh).positions {
position.z -= 2.0;
}
let mut glass = glass_slab(false).meshes.remove(0);
glass.name = "large index matched glazing".into();
for position in &mut Arc::make_mut(&mut glass.mesh).positions {
position.x *= 50.0;
position.y *= 50.0;
}
glass.surface = Some(OpaqueSurface::new(Vec3::ZERO, 0., 1., 1.).unwrap());
glass.transmission = Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, None).unwrap().with_shadow_transmission(true));
// Each 2x2-texel block has a flat bilinear centre. The two camera patches
// below see adjacent white/black details, not the texture's averaged mean.
let pixels: Vec<u8> = (0..16)
.flat_map(|y| {
(0..16).flat_map(move |x| {
let value = if (x / 2 + y / 2) & 1 == 0 { 255 } else { 0 };
[value, value, value, 255]
})
})
.collect();
let mut encoded = Vec::new();
image::codecs::png::PngEncoder::new(&mut encoded).write_image(&pixels, 16, 16, image::ExtendedColorType::Rgba8).unwrap();
let resources = Arc::new(
RuntimeTextures::new(vec![TextureBinding {
body_index: 0,
body_name: board.name.clone(),
frame: PlanarFrame { origin: [-0.125, -0.125, 0.], u: [2., 0., 0.], v: [0., 2., 0.] },
normal_strength: 1.,
base_color: Some(TextureMap::new_portable(encoded, MapRole::BaseColor).unwrap()),
normal: None,
roughness: None,
metallic: None,
base_color_mode: BaseColorMode::Replace,
flip_v: false,
}])
.unwrap(),
);
let render = |with_glass, centre_x| {
let mut scene = ProductScene { bounds: board.mesh.bounds(), meshes: vec![board.clone()] };
if with_glass {
scene.bounds = scene.bounds.union(&glass.mesh.bounds());
scene.meshes.push(glass.clone());
}
let mut image = request(32);
image.camera.target = Vec3::new(centre_x, 0., -1.5);
image.camera.fov = 0.02;
image.textures = Some(resources.clone());
let mut task = Task::new(
executor.context.clone(),
scene,
image,
JobOptions { samples: 1, max_depth: if with_glass { 3 } else { 1 }, seed: 1599, ..Default::default() },
CancelToken::default(),
)
.unwrap();
assert_eq!(task.opaque_scene, !with_glass);
task.complete_sample().unwrap();
task.read_linear().unwrap()
};
// The camera-to-board path is about 4mm, including a 1mm glass/wood gap.
// Closed-glass hit origins split a +/-500mm vertex anchor from the full
// barycentric displacement. Ignoring that low component invents roughly
// 1400mm of travel and selects coarse checker mips instead of these details.
let unit_reflectance = (3.0 * 0.8 + 1.0 * 0.6 + 1.5 * 0.8) / std::f64::consts::PI;
for (centre_x, reflectance) in [(0., 1.), (0.25, 0.)] {
let direct = render(false, centre_x);
let through_glass = render(true, centre_x);
for (pixel, (actual, expected)) in through_glass.iter().zip(&direct).enumerate() {
assert_eq!(expected[3], 1.0, "direct patch {centre_x}, pixel={pixel}");
assert_eq!(actual[3], 1.0, "glazed patch {centre_x}, pixel={pixel}");
for (actual, expected) in actual.iter().take(3).zip(expected) {
assert!((f64::from(*expected) - reflectance * unit_reflectance).abs() < 2e-5, "direct patch {centre_x}, pixel={pixel}: {expected}");
assert!((actual - expected).abs() < 2e-5, "glazed patch {centre_x}, pixel={pixel}: {actual} vs {expected}");
}
}
}
}
#[test]
@@ -2963,7 +3569,7 @@ fn gpu_scalar_maps_match_linear_reference_without_touching_ior() {
layout: Some(&layout),
module: &shader,
entry_point: Some("texture_scalar_reference"),
compilation_options: Default::default(),
compilation_options: wgpu::PipelineCompilationOptions { constants: &[("HAS_TEXTURES", 1.0)], ..Default::default() },
cache: None,
});
let mut input = request(2);
@@ -3281,6 +3887,13 @@ fn engine_exports_raw_master_from_the_exact_completed_job_without_png_conversion
drop(handle);
assert!(host.admitted_bytes() > 0);
drop(frame);
// Completion notification precedes worker-owned resource destruction.
// Require the actual reservation to drain after the final frame lease drops.
let released_by = std::time::Instant::now() + std::time::Duration::from_secs(5);
while host.admitted_bytes() != 0 {
assert!(std::time::Instant::now() < released_by, "worker did not release its exported frame reservation");
std::thread::sleep(std::time::Duration::from_millis(1));
}
assert_eq!(host.admitted_bytes(), 0);
std::fs::remove_dir_all(root).unwrap();
}
+83 -7
View File
@@ -1,10 +1,14 @@
//! One read-only storage buffer: body lookup, planar records and linear RGBA pixels.
//! One read-only storage buffer: body lookup, planar records and linear RGBA mip chains.
use solidcore_record::Vec3;
use solidcraft_geom::prelude::*;
use solidcraft_render::job::{
CancelToken, ErrorCode, JobError, Result,
textures::{BaseColorMode, RuntimeTextures, TextureMap},
};
use solidcraft_render::texture_sampling::{
TextureView,
mips::{MAX_MIP_TAIL_BYTES, MipChain},
};
fn vector(a: [f64; 3]) -> Vec3 {
Vec3::new(a[0], a[1], a[2])
@@ -30,12 +34,44 @@ fn pixels(
return Ok(*record);
}
let rgba = map.decode(cancel)?;
let view = TextureView::new(&rgba, map.dimensions()).map_err(|error| JobError::new(ErrorCode::InvalidRequest, error.to_string()))?;
// Decode roles before averaging: reflectance is linear sRGB; scalar and
// tangent-normal channels remain linear data. Alpha never participates.
// Existing temporary and saved built-in maps keep their level-zero sampler.
// Do not generate or retain an unused tail for those legacy inputs.
let mips = if map.gpu_mip_filtering() {
Some(MipChain::prepare(view, MAX_MIP_TAIL_BYTES, || cancel.is_cancelled()).map_err(|error| {
JobError::new(if cancel.is_cancelled() { ErrorCode::Cancelled } else { ErrorCode::InvalidRequest }, error.to_string())
})?)
} else {
None
};
let level_count = mips.as_ref().map_or(1, MipChain::level_count);
let offset = bytes.len() / 4;
for (index, value) in rgba.into_iter().enumerate() {
if index % 4096 == 0 {
cancel.check()?;
let descriptor_words = 4 + level_count * 4;
bytes.resize(bytes.len() + descriptor_words * 4, 0);
write_word(bytes, offset, level_count as u32)?;
write_word(bytes, offset + 1, 2)?;
write_word(bytes, offset + 2, u32::from(map.gpu_mip_filtering()))?;
for level in 0..level_count {
let (pixels, dimensions) = match &mips {
Some(mips) => (
mips.level(level).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing prepared GPU mip pixels"))?,
mips.dimensions(level).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing prepared GPU mip dimensions"))?,
),
None => (view, map.dimensions()),
};
let descriptor = offset + 4 + level * 4;
let pixel_offset = u32::try_from(bytes.len() / 4).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "GPU mip buffer offset overflow"))?;
write_word(bytes, descriptor, pixel_offset)?;
write_word(bytes, descriptor + 1, dimensions[0])?;
write_word(bytes, descriptor + 2, dimensions[1])?;
for (index, value) in pixels.rgba().iter().enumerate() {
if index % 4096 == 0 {
cancel.check()?;
}
bytes.extend_from_slice(&value.to_le_bytes());
}
bytes.extend_from_slice(&value.to_le_bytes());
}
let record = (u32::try_from(offset).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "texture buffer offset overflow"))?, map.dimensions());
shared.insert(map.identity(), record);
@@ -45,9 +81,11 @@ pub(super) fn flatten(resources: Option<&RuntimeTextures>, body_count: usize, or
let Some(resources) = resources else {
return Ok(vec![0; 16]);
};
let header = 4 + body_count + 1;
let header = (4 + body_count + 1).next_multiple_of(4);
let record_words = resources.bindings().len() * 24;
let mut bytes = super::scene::reserved((header + record_words) * 4 + resources.summary().linear_pixel_bytes as usize)?;
let capacity = usize::try_from(packed_bytes(resources, body_count))
.map_err(|_| JobError::new(ErrorCode::LimitExceeded, "GPU mip buffer capacity overflow"))?;
let mut bytes = super::scene::reserved(capacity)?;
bytes.resize((header + record_words) * 4, 0);
write_word(&mut bytes, 0, (body_count + 1) as u32)?;
let mut shared = std::collections::BTreeMap::new();
@@ -70,6 +108,15 @@ pub(super) fn flatten(resources: Option<&RuntimeTextures>, body_count: usize, or
let (normal, normal_size) = pixels(&mut bytes, binding.normal.as_ref(), cancel, &mut shared)?;
let (roughness, roughness_size) = pixels(&mut bytes, binding.roughness.as_ref(), cancel, &mut shared)?;
let (metallic, metallic_size) = pixels(&mut bytes, binding.metallic.as_ref(), cancel, &mut shared)?;
let roles = if metallic != 0 {
4
} else if roughness != 0 {
3
} else if normal != 0 {
2
} else {
1
};
let flags = u32::from(binding.flip_v) | (u32::from(binding.base_color_mode == BaseColorMode::Replace) << 1);
for (offset, value) in [
(3, base),
@@ -86,6 +133,7 @@ pub(super) fn flatten(resources: Option<&RuntimeTextures>, body_count: usize, or
(20, metallic),
(21, metallic_size[0]),
(22, metallic_size[1]),
(23, roles),
] {
write_word(&mut bytes, record + offset, value)?;
}
@@ -93,3 +141,31 @@ pub(super) fn flatten(resources: Option<&RuntimeTextures>, body_count: usize, or
cancel.check()?;
Ok(bytes)
}
/// Exact packed storage admission for the admitted dimensions and filtering policy.
/// Count each content/role/policy once, including only level zero for legacy maps.
pub(super) fn packed_bytes(resources: &RuntimeTextures, body_count: usize) -> u64 {
let bindings = resources.bindings().len() as u64;
let mut bytes = 4 * ((5 + body_count as u64).next_multiple_of(4) + bindings * 24);
let mut seen = std::collections::BTreeSet::new();
for binding in resources.bindings() {
for map in [&binding.base_color, &binding.normal, &binding.roughness, &binding.metallic].into_iter().flatten() {
if !seen.insert(map.identity()) {
continue;
}
let [mut width, mut height] = map.dimensions().map(u64::from);
let mut levels = 1;
let mut pixels = width * height;
if map.gpu_mip_filtering() {
while width > 1 || height > 1 {
width = (width / 2).max(1);
height = (height / 2).max(1);
pixels += width * height;
levels += 1;
}
}
bytes += (4 + levels * 4) * 4 + pixels * 16;
}
}
bytes
}
+140 -34
View File
@@ -2,19 +2,24 @@
fn texture_vector(word:u32)->vec3<f32> {
return bitcast<vec3<f32>>(vec3<u32>(texture_words[word],texture_words[word+1u],texture_words[word+2u]));
}
fn texture_record(t:Triangle)->u32 {
let body=u32(t.optics.w);
fn texture_record(body_id:f32)->u32 {
if !HAS_TEXTURES {return 0u;}
let body=u32(body_id);
if body>=texture_words[0] {return 0u;}
return texture_words[4u+body];
}
fn texture_pixel(offset:u32,width:u32,x:u32,y:u32)->vec3<f32> {
return texture_vector(offset+4u*(y*width+x));
}
fn texture_sample(offset:u32,size:vec2<u32>,uv:vec2<f32>)->vec3<f32> {
fn texture_bilinear(offset:u32,size:vec2<u32>,uv:vec2<f32>)->vec3<f32> {
let position=fract(uv)*vec2<f32>(size)-vec2<f32>(0.5);
let lower=vec2<i32>(floor(position));
let first=vec2<u32>((lower+vec2<i32>(size))%vec2<i32>(size));
let second=(first+vec2<u32>(1u))%size;
// fract restricts lower to[-1,size-1]. Avoid integer modulo after a BVH
// walk: native shader compilers have already failed on that pattern.
let bounded=vec2<u32>(max(lower,vec2<i32>(0)));
let first=select(bounded,size-vec2<u32>(1u),lower<vec2<i32>(0));
let next=first+vec2<u32>(1u);
let second=select(next,vec2<u32>(0u),next>=size);
let fraction=fract(position);
let a=texture_pixel(offset,size.x,first.x,first.y);
let b=texture_pixel(offset,size.x,second.x,first.y);
@@ -22,36 +27,120 @@ fn texture_sample(offset:u32,size:vec2<u32>,uv:vec2<f32>)->vec3<f32> {
let d=texture_pixel(offset,size.x,second.x,second.y);
return mix(mix(a,b,fraction.x),mix(c,d,fraction.x),fraction.y);
}
struct TextureGradients { dx:vec2<f32>, dy:vec2<f32> };
fn texture_lod(size:vec2<u32>,gradients:TextureGradients,last:u32)->f32 {
// Same largest-singular-value policy as select_isotropic_lod. Differentiate
// unwrapped coordinates: crossing a repeat seam never enlarges a footprint.
let columns=vec4<f32>(gradients.dx*vec2<f32>(size),gradients.dy*vec2<f32>(size));
let magnitude=abs(columns);
let scale=max(max(magnitude.x,magnitude.y),max(magnitude.z,magnitude.w));
if scale<=0.0 {return 0.0;}
let q=columns/scale;
let a=dot(q.xy,q.xy);let b=dot(q.zw,q.zw);let c=dot(q.xy,q.zw);
let radius=scale*sqrt(max(0.0,0.5*(a+b+length(vec2<f32>(a-b,2.0*c)))));
return clamp(log2(max(radius,1.0)),0.0,f32(last));
}
fn texture_level(descriptor:u32,level:u32,uv:vec2<f32>)->vec3<f32> {
let record=descriptor+4u+level*4u;
return texture_bilinear(texture_words[record],vec2<u32>(texture_words[record+1u],texture_words[record+2u]),uv);
}
fn texture_sample(descriptor:u32,size:vec2<u32>,uv:vec2<f32>,gradients:TextureGradients)->vec3<f32> {
let last=texture_words[descriptor]-1u;
var lod=0.0;
if last>0u {lod=texture_lod(size,gradients,last);}
let low=u32(floor(lod));let high=min(low+1u,last);
let count=min(texture_words[descriptor+1u],select(2u,1u,low==high || fract(lod)==0.0));
var color=vec3<f32>(0.0);
// One bilinear call site keeps native compilation bounded when this sampler
// shares a path with glass traversal. The admitted descriptor allows 1..2 levels.
for(var sample=0u;sample<count;sample+=1u) {
let rgb=texture_level(descriptor,select(low,high,sample>0u),uv);
if sample==0u {color=rgb;} else {color=mix(color,rgb,fract(lod));}
}
return color;
}
fn texture_uv(record:u32,position:vec3<f32>)->vec2<f32> {
let delta=position-texture_vector(record);
let uv=vec2<f32>(dot(delta,texture_vector(record+4u)),dot(delta,texture_vector(record+8u)));
return vec2<f32>(uv.x,select(uv.y,-uv.y,(texture_words[record+19u]&1u)!=0u));
}
fn texture_surface(t:Triangle,position:vec3<f32>)->Triangle {
let record=texture_record(t);var result=t;
if record==0u {return result;}
let uv=texture_uv(record,position);
if texture_words[record+3u]!=0u {
let rgb=texture_sample(texture_words[record+3u],vec2<u32>(texture_words[record+7u],texture_words[record+11u]),uv);
let replace=(texture_words[record+19u]&2u)!=0u;
result.base=vec4<f32>(select(t.base.xyz*rgb,rgb,replace),t.base.w);
}
// Scalar maps are linear data, never sRGB. They replace the corresponding
// captured optical parameter; alpha, IOR, coat and medium identity survive.
if texture_words[record+16u]!=0u {
let roughness=texture_sample(texture_words[record+16u],vec2<u32>(texture_words[record+17u],texture_words[record+18u]),uv).x;
result.parameters.y=clamp(roughness,0.045,1.0);
}
if texture_words[record+20u]!=0u {
let metallic=texture_sample(texture_words[record+20u],vec2<u32>(texture_words[record+21u],texture_words[record+22u]),uv).x;
result.parameters.x=clamp(metallic,0.0,1.0);
}
return result;
fn texture_plane_differential(normal:vec3<f32>,direction:vec3<f32>,delta:vec3<f32>)->vec3<f32> {
return delta-direction*(dot(normal,delta)/dot(normal,direction));
}
fn texture_normal(t:Triangle,position:vec3<f32>,n:vec3<f32>,geometric:vec3<f32>)->vec3<f32> {
let record=texture_record(t);
if record==0u || texture_words[record+12u]==0u {return n;}
let rgb=texture_sample(texture_words[record+12u],vec2<u32>(texture_words[record+13u],texture_words[record+14u]),texture_uv(record,position));
fn texture_camera_direction_delta(direction:vec3<f32>,delta:vec3<f32>)->vec3<f32> {
// Fixed-lens focus_scale/length(q) equals forward cosine / camera distance.
// Divide the pixel delta first to avoid a large intermediate reciprocal.
let scaled=delta/u.back.w;
return (scaled-direction*dot(direction,scaled))*dot(direction,-unit(u.back.xyz));
}
fn texture_world_gradients(record:u32,dx:vec3<f32>,dy:vec3<f32>)->TextureGradients {
let inverse_u=texture_vector(record+4u);let inverse_v=texture_vector(record+8u);
let sign_v=select(1.0,-1.0,(texture_words[record+19u]&1u)!=0u);
return TextureGradients(vec2<f32>(dot(dx,inverse_u),dot(dx,inverse_v)*sign_v),vec2<f32>(dot(dy,inverse_u),dot(dy,inverse_v)*sign_v));
}
fn texture_gradients(record:u32,normal:vec3<f32>,direction:vec3<f32>,distance:f32,path_length:f32,bounce:u32)->TextureGradients {
if record==0u {return TextureGradients(vec2<f32>(0.0),vec2<f32>(0.0));}
if bounce==0u && abs(dot(normal,direction))>1e-6 {
var dx=2.0*u.right.xyz/f32(u.image.x);
var dy=-2.0*u.up.xyz/f32(u.image.y);
if u.eye.w>0.5 {
// For a fixed lens sample, focus_scale/length(q) is exactly the
// forward direction cosine / camera distance. Derive at this hit;
// no camera differential stays live across the medium stack.
dx=texture_camera_direction_delta(direction,dx)*distance;
dy=texture_camera_direction_delta(direction,dy)*distance;
}
dx=texture_plane_differential(normal,direction,dx);
dy=texture_plane_differential(normal,direction,dy);
return texture_world_gradients(record,dx,dy);
}
// Secondary paths use a finite camera-pixel cone, expanded by total path
// length and grazing angle; focused specular differentials are not tracked.
let pixel_span=2.0*max(length(u.right.xyz)/f32(u.image.x),length(u.up.xyz)/f32(u.image.y));
let distance_scale=select(1.0,path_length/max(u.back.w,1e-6),u.eye.w>0.5);
let span=min(pixel_span*distance_scale/max(abs(dot(normal,direction)),1e-6),1e20);
let axis=select(vec3<f32>(1.0,0.0,0.0),vec3<f32>(0.0,0.0,1.0),abs(normal.z)<0.9);
let tangent=unit(cross(normal,axis));
return texture_world_gradients(record,tangent*span,cross(normal,tangent)*span);
}
// Sampling changes RGB, metallic and roughness only. Transmission, IOR and
// thickness never cross the sampler boundary, even in mixed glass/map scenes.
struct TextureSurface { color:vec3<f32>, metallic:f32, roughness:f32, normal:vec4<f32> };
fn texture_surface(record:u32,color:vec3<f32>,metallic:f32,roughness:f32,position:vec3<f32>,gradients:TextureGradients,scalar_face:bool)->TextureSurface {
if record==0u {return TextureSurface(color,metallic,roughness,vec4<f32>(0.5,0.5,1.0,0.0));}
var mapped_color=color;
var mapped_metallic=metallic;
var mapped_roughness=roughness;
var mapped_normal=vec4<f32>(0.5,0.5,1.0,0.0);
let uv=texture_uv(record,position);
// A single sampling call site keeps the native path compiler from inlining
// four complete trilinear samplers while its traversal/medium state is live.
// The runtime bound excludes unused trailing roles and prevents unroll.
for(var role=0u;role<min(texture_words[record+23u],4u);role+=1u) {
var descriptor=texture_words[record+3u];
var size=vec2<u32>(texture_words[record+7u],texture_words[record+11u]);
if role==1u {descriptor=texture_words[record+12u];size=vec2<u32>(texture_words[record+13u],texture_words[record+14u]);}
if role==2u {descriptor=texture_words[record+16u];size=vec2<u32>(texture_words[record+17u],texture_words[record+18u]);}
if role==3u {descriptor=texture_words[record+20u];size=vec2<u32>(texture_words[record+21u],texture_words[record+22u]);}
if descriptor==0u {continue;}
// Only newly imported maps yield to explicit scalar face appearances.
// Existing built-in/temporary roles retain their previous precedence,
// including a request that mixes legacy and portable roles.
if scalar_face && texture_words[descriptor+2u]!=0u {continue;}
let rgb=texture_sample(descriptor,size,uv,gradients);
if role==0u {
let replace=(texture_words[record+19u]&2u)!=0u;
mapped_color=select(color*rgb,rgb,replace);
} else if role==1u {mapped_normal=vec4<f32>(rgb,1.0);}
// Scalars are linear data. Alpha, IOR, coat and medium identity survive.
else if role==2u {mapped_roughness=clamp(rgb.x,0.045,1.0);}
else {mapped_metallic=clamp(rgb.x,0.0,1.0);}
}
return TextureSurface(mapped_color,mapped_metallic,mapped_roughness,mapped_normal);
}
fn texture_normal(record:u32,sampled:vec4<f32>,n:vec3<f32>,geometric:vec3<f32>)->vec3<f32> {
if record==0u || sampled.w==0.0 {return n;}
let rgb=sampled.xyz;
let u=unit(texture_vector(record+4u));
let tangent=u-n*dot(n,u);
if dot(tangent,tangent)<1e-12 {return n;}
@@ -66,13 +155,30 @@ fn texture_normal(t:Triangle,position:vec3<f32>,n:vec3<f32>,geometric:vec3<f32>)
@compute @workgroup_size(1)
fn texture_reference() {
let t=triangle(0u);
let mapped=texture_surface(t,u.eye.xyz);
accumulation[0]=vec4<f32>(mapped.base.xyz,1.0);
accumulation[1]=vec4<f32>(texture_normal(t,u.eye.xyz,u.up.xyz,u.back.xyz)+vec3<f32>(2.0),1.0);
let record=texture_record(t.optics.w);
let gradients=TextureGradients(vec2<f32>(0.0),vec2<f32>(0.0));
let mapped=texture_surface(record,t.base.xyz,t.parameters.x,t.parameters.y,u.eye.xyz,gradients,(u32(t.interior.z)&2u)!=0u);
accumulation[0]=vec4<f32>(mapped.color,1.0);
accumulation[1]=vec4<f32>(texture_normal(record,mapped.normal,u.up.xyz,u.back.xyz)+vec3<f32>(2.0),1.0);
}
@compute @workgroup_size(1)
fn texture_scalar_reference() {
let t=texture_surface(triangle(0u),u.eye.xyz);
accumulation[0]=vec4<f32>(t.parameters.xyz,1.0);
let t=triangle(0u);
let mapped=texture_surface(texture_record(t.optics.w),t.base.xyz,t.parameters.x,t.parameters.y,u.eye.xyz,TextureGradients(vec2<f32>(0.0),vec2<f32>(0.0)),(u32(t.interior.z)&2u)!=0u);
accumulation[0]=vec4<f32>(vec3<f32>(mapped.metallic,mapped.roughness,t.parameters.z),1.0);
}
// Validation invokes the production trilinear sampler with explicit unwrapped
// gradients, independently of camera inference.
@compute @workgroup_size(1)
fn texture_mip_reference() {
let t=triangle(0u);let record=texture_record(t.optics.w);
let gradients=TextureGradients(u.right.xy,u.up.xy);
let mapped=texture_surface(record,t.base.xyz,t.parameters.x,t.parameters.y,u.eye.xyz,gradients,(u32(t.interior.z)&2u)!=0u);
accumulation[0]=vec4<f32>(mapped.color,1.0);
let last=texture_words[texture_words[record+3u]]-1u;
var lod=0.0;
if last>0u {lod=texture_lod(vec2<u32>(texture_words[record+7u],texture_words[record+11u]),gradients,last);}
accumulation[1]=vec4<f32>(lod,0.0,0.0,1.0);
}