#[cfg(all(test, not(target_arch = "wasm32")))] use super::INPUT_LAYER; use super::{MaterialUnderlay, generator_p2, generator_p3a, gpu_curvature, p3b}; use super::{ ANCHOR_PUBLISH_LAYER, ANCHOR_PUBLISH_MASK, Arc, BEGIN_GROUP, BTreeMap, BakedInputs, BakedMaps, BlendMode, COLOR_SELECTION_OPCODE, Channel, CompositeRegion, ContentsOffset, DisplayKind, END_GROUP, Effect, EffectKind, EnvironmentSh, FilterPlan, GeometryMasks, GpuStencil, GroupPlan, IdBake, ImageStore, LOOKUP_WORDS, LateEnvironment, LayerId, LayerKind, LiveBrush, MaterialImages, Mesh, NO_TRI, NOOP_EFFECT_OPCODE, Operation, PaintInputs, PixelStore, ProceduralInputs, Project, Source, StackWork, TILE_GENERATOR_OPCODE, TileImage, TilePatterns, UvGBuffer, Zeroable, bind_generator_sources, bind_input_sources, bind_tile_source, blend_code, blends_per_channel, channel_filter, channel_slot, compile_mask, content_depends_on_channel, content_deposit, content_filter, content_paint, display_bit, fill_projection, groups, needs_surface, packages, placed, register_decal, source_operation, sparse_channel, stack, udim, }; #[derive(Debug)] pub struct CompositeProgram { pub(super) underlay: Option>, pub(super) operations: Vec, pub(super) layer_count: u32, pub(super) filters: FilterPlan, pub(super) groups: GroupPlan, pub(super) geometry: GeometryMasks, pub(super) paint: Vec, pub(super) ramp_words: Vec, pub(super) curvature_sizes: [bool; gpu_curvature::SIZES], pub(super) tile_patterns: TilePatterns, pub(super) material_images: MaterialImages, pub(super) brush_alpha: Option, pub(super) brush_stencil: Option, /// A live clone's or smudge's carried values on the device pub(super) brush_carried: Option, pub(crate) region: Option, pub(super) coverage: Option<(Arc, u32)>, pub(super) surface: Option<(Arc, Arc)>, pub(super) needs_surface: bool, pub(super) baked: Option, pub(super) id_bake: Option, pub(super) display_outputs: u32, pub(super) glossiness: bool, pub(super) mix_baked_ao: bool, pub(super) mask_preview: bool, pub(super) mask_layer: u32, /// The first operation of each draw of a layer with a mask, with the draw's placement pub(super) mask_layers: Vec<(LayerId, ContentsOffset, u32)>, /// Side-table words to fill with image record offsets at upload (`ProceduralInputs::pack_image`) pub(super) image_words: Vec<(u32, u32)>, /// The environment's diffuse light the program reads (`ProceduralInputs::reserve_environment`) pub(super) environment: Option, /// Upload the second bake row block (`ProceduralInputs::read_bake_rows`) pub(super) bake_rows: bool, /// P8: the side-table record of a UV tile atlas (`udim::bind`), 0 for a classic set pub(super) udim: u32, /// P8: the UV tile atlas's blocks, which say where a level stage has texels to filter pub(super) udim_layout: Option, /// P3b: the whole-map generator fields the program reads pub(super) p3b_fields: p3b::FieldPlan, /// P2: the micro details the generators read pub(super) micro: generator_p2::MicroPlan, /// A layer thumbnail's output (`set_thumbnail`): mode, channel slot, display encoding, 0 pub(super) thumb: [u32; 4], } impl CompositeProgram { /// Maximum size of a resident linear material underlay for this device. pub fn material_underlay_limit(limits: &wgpu::Limits) -> u64 { if limits.max_storage_buffers_per_shader_stage >= 7 && limits.max_bindings_per_bind_group >= 20 { limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) } else { 0 } } /// Start the layer stack from the CPU material before display conversion. pub fn set_material_underlay(&mut self, underlay: Arc) -> Result<(), &'static str> { if self.mask_preview || self.filters.stages.iter().any(|stage| stage.anchor.is_some()) { return Err("The GPU layer stack reads across the CPU material boundary."); } for channel in Channel::ALL.into_iter().filter(|&channel| underlay.has_channel(channel)) { self.display_outputs |= display_bit(DisplayKind::of_channel(channel)); } self.underlay = Some(underlay); Ok(()) } pub fn is_neutral(&self) -> bool { !self.mask_preview && !self.is_thumbnail() && !self.glossiness && self.underlay.is_none() && self.layer_count == 0 && self.baked.as_ref().is_none_or(|baked| baked.maps[0].is_none() && baked.maps[1].is_none()) } pub fn is_mask_preview(&self) -> bool { self.mask_preview } /// Write a layer thumbnail of `channel` into the grayscale view's slot instead of the display /// maps: with `flat`, the program's draws of `channel` composited over nothing (straight /// value, coverage as alpha; a paint or fill layer drawn alone); otherwise the composited /// channel (a folder over the channel defaults). Texels no triangle covers are transparent. /// Call before `set_surface_inputs`, which then reads coverage without padding. pub fn set_thumbnail(&mut self, channel: Channel, flat: bool) -> Result<(), &'static str> { if self.mask_preview || self.underlay.is_some() { return Err("A thumbnail reads a material program's own draws."); } let encoding = match channel.kind() { super::ChannelKind::Color => 0, super::ChannelKind::Signed => 1, super::ChannelKind::Scalar | super::ChannelKind::NormalMap => 2, }; self.thumb = [if flat { 1 } else { 2 }, super::channel_slot(channel), encoding, 0]; self.display_outputs = display_bit(DisplayKind::BaseColor); Ok(()) } /// Write a brush's pickup source instead of the display maps or the thumbnail: `channels` /// (one channel of three components, or up to four scalar channels) as the CPU stores them /// (16 bits, signed values around mid gray), one RGBA16 texel per texel in the Normal map's /// place; texels outside the set are 0. Call on a composited-channel thumbnail (the /// document's values) or a mask preview (the mask's value, `channels` its one channel). pub fn set_pickup_output(&mut self, channels: &[Channel]) -> Result<(), &'static str> { let colors = channels.iter().any(|channel| channel.components() == 3); if channels.is_empty() || channels.len() > 4 || (colors && channels.len() > 1) || !(self.mask_preview || self.thumb[0] == 2) { return Err("A pickup source is one channel of three components or up to four scalar channels."); } let (mut slots, mut encodings) = (0, 0); for (k, &channel) in channels.iter().enumerate() { let encoding = match channel.kind() { _ if channel.components() == 3 => 0, super::ChannelKind::Signed => 1, _ => 2, }; slots |= super::channel_slot(channel) << (8 * k); encodings |= encoding << (2 * k); } self.thumb[1..4].copy_from_slice(&[slots, encodings, channels.len() as u32]); self.display_outputs = display_bit(DisplayKind::Normal); Ok(()) } /// Whether the program writes a layer thumbnail ([`Self::set_thumbnail`]) pub fn is_thumbnail(&self) -> bool { self.thumb[0] != 0 } /// Work per output texel that sizes bands and submissions: Tile Generator placements per /// plane and sample, and what P1 declares for its fills (`fill_projection::work_per_texel`: /// symmetry copies times sampling cost). pub(super) fn tile_work_per_pixel(&self) -> Result { self.operations.iter().try_fold(0u64, |work, op| { let mut own = 0; if op.ids[1] == TILE_GENERATOR_OPCODE { let tile_work = self.tile_patterns.work_per_sample(op.high[3] as usize).ok_or("A Tile Generator operation has no settings.")?; let planes = if op.procedural[3] == 1 { 3 } else { 1 }; let samples = if op.procedural[0] == 0 { 1 } else { 4 }; own = tile_work.saturating_mul(planes * samples); } Ok(work.saturating_add(fill_projection::work_per_texel(op, own))) }) } pub(crate) fn writes_display(&self, kind: DisplayKind) -> bool { self.display_outputs & display_bit(kind) != 0 } /// Let the shader sample the nearest covered UV texel for island padding. pub fn set_coverage(&mut self, coverage: Arc, radius: u32) { self.coverage = Some((coverage, if self.mask_preview || self.is_thumbnail() { 0 } else { radius.min(15) })); } /// Resolve named images used by authored fills, decals and Tile Generators, and the /// environment's diffuse light (an imported environment is an image). pub fn set_tile_images(&mut self, images: &ImageStore) { self.tile_patterns.set_images(images); self.material_images.set_images(images); self.micro.set_images(images); if let Some(environment) = &mut self.environment { environment.set(&EnvironmentSh::of(&environment.display, images)); } } /// The environment and rotation (degrees) the program lights with, from the compiled /// project's display settings; None when nothing reads the environment. A viewport compiles /// again when either changes (or the imported environment image does). pub fn environment(&self) -> Option<(&str, f32)> { self.environment.as_ref().map(|environment| (environment.display.environment.as_str(), environment.display.env_rotation)) } /// Tests: the stage of the layer's Height operation and the stage reading it as its input. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn input_stages(&self) -> (usize, usize) { let stages = &self.filters.stages; let height = stages.iter().position(|stage| self.operations[stage.layer as usize].ids[0] == channel_slot(Channel::Height)); let reader = stages.iter().position(|stage| stage.input_kind == INPUT_LAYER); (height.unwrap_or(usize::MAX), reader.unwrap_or(usize::MAX)) } /// Tests: each whole-set pass's stage count and reach past the set's edges. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn whole_set_passes(&self) -> Vec<(usize, u32)> { self.filters.whole_set().map_or_else(Vec::new, |whole| whole.passes.iter().map(|pass| (pass.stages.len(), pass.past_edges)).collect()) } /// Tests: the last stage's input and input kind. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn input_of_last_stage(&self) -> (u32, u32) { self.filters.stages.last().map_or((u32::MAX, u32::MAX), |stage| (stage.input, stage.input_kind)) } /// Replace the environment's diffuse light (tests: a stub reader instead of `EnvironmentSh::of`). #[cfg(test)] pub(super) fn set_environment(&mut self, environment: &EnvironmentSh) { if let Some(late) = &mut self.environment { late.set(environment); } } /// Mesh-space projections and generators share the viewport's surface and bake inputs. pub fn set_surface_inputs(&mut self, mesh: &Arc, gbuf: &Arc, baked: Option<&BakedMaps>) -> Result<(), &'static str> { // P1's projector depth grids, before the atlas reads them self.material_images.set_surface(mesh); if self.needs_surface || !self.geometry.parts.is_empty() { self.surface = Some((mesh.clone(), gbuf.clone())); } self.geometry.resolve(mesh); // P3a and P1: the mesh's bounds the 3D generators and the generator controls scale their position by generator_p3a::bind_bounds(&mut self.operations, mesh); // P3b: what the whole-map generator fields read self.p3b_fields.set_inputs(mesh, gbuf, baked); // P2: what the micro details read self.micro.set_surface_inputs(mesh, gbuf, baked)?; // Texels no triangle covers keep the channels' defaults, as the CPU leaves them let partly_covered = gbuf.tri.contains(&NO_TRI); if self.mask_preview || self.is_thumbnail() || ((partly_covered || !self.filters.stages.is_empty() || !self.geometry.parts.is_empty()) && self.coverage.is_none()) { self.set_coverage(gbuf.clone(), 0); } self.baked = baked.map(|baked| BakedInputs::new(baked, self.bake_rows)).transpose()?.flatten(); self.id_bake = baked.filter(|_| self.operations.iter().any(|op| op.ids[1] == COLOR_SELECTION_OPCODE && op.procedural[2] != 0)).and_then(IdBake::new); // A thumbnail writes only its own output (a pickup source selects the Normal map itself) if !self.mask_preview && !self.is_thumbnail() && self.baked.as_ref().is_some_and(|baked| baked.maps[1].is_some()) { self.display_outputs |= display_bit(DisplayKind::Normal); } Ok(()) } /// A flat stack of sparse paint, solid and UV procedural fills, masks and point effects. /// Disabled layers need no work. Stacks outside this evaluator's domain use the CPU. pub fn compile(project: &Project, pixels: &PixelStore, ts: usize) -> Option { Self::compile_region(project, pixels, ts, None) } pub fn compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option) -> Option { Self::try_compile_region(project, pixels, ts, region).ok() } /// Also provide the reason the viewport must select its CPU compositor. pub fn try_compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option) -> Result { Self::try_compile_with_brush(project, pixels, ts, region, None) } pub fn try_compile_with_brush( project: &Project, pixels: &PixelStore, ts: usize, region: Option, brush: Option, ) -> Result { Self::try_compile_above(project, pixels, ts, 0, region, brush) } /// Compile the draws after a root-level CPU material boundary. pub fn try_compile_above( project: &Project, pixels: &PixelStore, ts: usize, first_layer: usize, region: Option, brush: Option, ) -> Result { let mut remaining = generator_p2::MAX_CAPTURE_PROGRAMS; Self::compile_with_capture_budget(project, pixels, ts, first_layer, region, brush, &mut remaining) } pub(super) fn compile_with_capture_budget( project: &Project, pixels: &PixelStore, ts: usize, first_layer: usize, region: Option, brush: Option, remaining: &mut usize, ) -> Result { Self::compile_draws(project, pixels, ts, (first_layer, false), region, brush, remaining) } /// A layer thumbnail of `channel` ([`Self::set_thumbnail`]). A flat thumbnail draws fills /// of the channel's default value too: over nothing they show it with full coverage. pub fn try_compile_thumbnail(project: &Project, pixels: &PixelStore, ts: usize, channel: Channel, flat: bool) -> Result { let mut remaining = generator_p2::MAX_CAPTURE_PROGRAMS; let mut program = Self::compile_draws(project, pixels, ts, (0, flat), None, None, &mut remaining)?; program.set_thumbnail(channel, flat)?; Ok(program) } /// The draws of the stack from `first_layer`; with `draw_neutral`, also fills that only /// reset a channel to its default before anything wrote it fn compile_draws( project: &Project, pixels: &PixelStore, ts: usize, (first_layer, draw_neutral): (usize, bool), region: Option, brush: Option, remaining: &mut usize, ) -> Result { let set = project.texture_sets.get(ts).ok_or("The texture set is missing.")?; let stack = set.stack.get(first_layer..).ok_or("The CPU material boundary is outside the layer stack.")?; packages::check_set(set, false)?; if let Some(brush) = &brush { brush.validate(set.size())?; } let mut operations: Vec = Vec::new(); let mut paint = PaintInputs::default(); let mut tile_patterns = TilePatterns::default(); let mut effects = Vec::new(); let mut procedural = ProceduralInputs::new(set.resolution); // P8: a UV tile atlas's block, its tile scales and the set's own resolution let layout = udim::UdimLayout::of(set); udim::prepare(layout.as_ref(), &mut procedural); let mut geometry = GeometryMasks::default(); let mut groups = GroupPlan::default(); let mut group_depth = 0; let mut mask_layers = Vec::new(); let mut non_default = [first_layer != 0 || draw_neutral; Channel::ALL.len()]; let stencil_pigment = brush.as_ref().is_some_and(|brush| brush.stencil.as_ref().is_some_and(|stencil| stencil.colors)); // Each draw carries the Scale and Rotation of the folders holding it (an instanced folder's too) let mut layers: Vec<_> = stack.iter().rev().map(|&id| (StackWork::Layer(id, 0, 0), ContentsOffset::NONE)).collect(); while let Some((work, around)) = layers.pop() { let (id, depth, inherited_geometry) = match work { StackWork::Layer(id, depth, geometry) => (id, depth, geometry), StackWork::EndGroup(start) => { let end = operations.len() as u32 + 1; let weights = operations[start].ids[2]; operations[start].ids[3] = end; operations.push(Operation { ids: [0, END_GROUP, weights, 0], ..Operation::zeroed() }); group_depth -= 1; continue; } }; let own = project.layers.get(&id).ok_or("A layer is missing from the material.")?; if !own.visible { continue; } let Some(layer) = project.content_layer(id) else { continue }; let geometry_mask = geometry.register(inherited_geometry, own.geometry_mask.as_deref()); let mask = project.layers.get(&project.mask_owner(id)).and_then(|owner| owner.mask.as_ref()).filter(|m| m.enabled); let reads_below_cut = |effect: &Effect| effect.visible && (effect.reads(None) || effect.kind.reads_stack()); let mask_reads_below_cut = || first_layer != 0 && mask.is_some_and(|mask| mask.effects.iter().any(reads_below_cut)); if let LayerKind::Group { children, contents, .. } = &layer.kind { if depth > texturecraft_core::project::MAX_DEPTH { continue; } // A folder's Scale and Rotation (an instanced folder's too) re-place every fill inside it let children_around = around.then(*contents); // Keep the group boundary when anchors escape its geometry restriction if mask.is_none() && set.channels.iter().all(|&(channel, _)| { layer.blend(channel).is_some_and(|blend| blend.mode != BlendMode::Disable && blend.opacity.is_finite() && blend.opacity >= 1.0) }) && (geometry_mask == 0 || !groups::children_publish_anchors(project, children, depth + 1)) { layers.extend(children.iter().rev().map(|&child| (StackWork::Layer(child, depth + 1, geometry_mask), children_around))); continue; } let mut weights = [0.0f32; Channel::ALL.len()]; for &(channel, _) in &set.channels { if let Some(blend) = layer.blend(channel).filter(|blend| blend.mode != BlendMode::Disable) { if !blend.opacity.is_finite() { return Err("A group has an invalid opacity."); } weights[channel_slot(channel) as usize] = blend.opacity.clamp(0.0, 1.0); } } if weights.iter().all(|&opacity| opacity == 0.0) && mask.is_none_or(|mask| !mask.effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor))) { continue; } if mask_reads_below_cut() { return Err("The GPU layer stack reads across the CPU material boundary."); } let begin = effects.len() as u32; let background = compile_mask(mask, around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut effects)?; let count = effects.len() as u32 - begin; // A folder's This Layer is the stack below it, as the CPU reads it effects[begin as usize..].iter_mut().for_each(stack::read_folder_layers); let height = layer.height_mask; let height_params = if height.enabled && count != 0 { if !height.contrast.is_finite() || !height.offset.is_finite() { return Err("A group's height mask has invalid parameters."); } [height.contrast.to_bits(), height.offset.to_bits()] } else { [0; 2] }; let weight_offset = u32::try_from(procedural.ramp_words.len()) .ok() .and_then(|len| LOOKUP_WORDS.checked_add(len)) .ok_or("The GPU group settings are too large.")?; procedural.ramp_words.extend(weights.map(f32::to_bits)); let open = operations.len(); let mut op = Operation { ids: [0, BEGIN_GROUP, weight_offset, 0], effects: [begin, count, 0, 0], constraints: [geometry_mask, 0, height_params[0], height_params[1]], ..Operation::zeroed() }; op.balance[1] = background; operations.push(op); mask_layers.push((id, around, open as u32)); procedural.anchors.draw_ranges.push(open as u32..open as u32 + 1); group_depth += 1; groups.depth = groups.depth.max(group_depth); layers.push((StackWork::EndGroup(open), ContentsOffset::NONE)); // The group tests its geometry before entering. Children still apply their own masks layers.extend(children.iter().rev().map(|&child| (StackWork::Layer(child, depth + 1, 0), children_around))); continue; } // A visible instance draws its resolved content and its effective mask if mask_reads_below_cut() || (first_layer != 0 && layer.content_effects.iter().any(reads_below_cut)) { return Err("The GPU layer stack reads across the CPU material boundary."); } let mask_start = effects.len() as u32; let mask_background = compile_mask(mask, around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut effects)?; let shared_content = effects.len() as u32; let mask_count = shared_content - mask_start; let has_content_anchors = layer.content_effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor)); if mask_background == 0.0 && mask_count == 0 && !has_content_anchors { continue; } let mut content_anchors = Vec::new(); let mut visible_cut = 0u32; let per_channel = layer.content_effects.iter().any(|effect| effect.visible && (content_depends_on_channel(effect) || blends_per_channel(effect))); let mut templates = Vec::new(); for effect in layer.content_effects.iter().filter(|e| e.visible) { if matches!(effect.kind, EffectKind::Anchor) { content_anchors.push((effect.id, visible_cut)); continue; } visible_cut += 1; // A filter laid on each channel apart is lowered once per channel of the set let channel_ops = if blends_per_channel(effect) && !content_depends_on_channel(effect) { let mut ops = BTreeMap::new(); for &(channel, _) in &set.channels { let first_input = procedural.input_sources.len(); let op = channel_filter(effect, channel, &mut procedural).ok_or("A layer effect uses CPU compositing.")?; stack::bind_input_tiles(effect, &mut procedural.input_sources[first_input..], &mut tile_patterns); ops.insert(channel, (procedural.preceding_stage.take(), op)); } Some(ops) } else { None }; let op = if content_depends_on_channel(effect) || channel_ops.is_some() { None } else { let first_input = procedural.input_sources.len(); let op = content_filter(effect, &mut procedural).ok_or("A layer effect uses CPU compositing.")?; stack::bind_input_tiles(effect, &mut procedural.input_sources[first_input..], &mut tile_patterns); Some(op) }; // A lowering with a stage before its operation takes two operations, on every channel alike let mut stage = procedural.preceding_stage.take(); if channel_ops.as_ref().is_some_and(|ops| ops.values().any(|(channel_stage, _)| channel_stage.is_some())) { stage = Some(Operation { ids: [0, NOOP_EFFECT_OPCODE, 0, 0], ..Operation::zeroed() }); } visible_cut += u32::from(stage.is_some()); if per_channel { templates.push((effect, stage, op, channel_ops)); } else if let Some(op) = op { effects.extend(stage); effects.push(op); } } let fill = match &layer.kind { LayerKind::Fill(fill) => Some(fill), LayerKind::Paint => None, _ => return Err("A group or another layer type uses CPU compositing."), }; let decal = fill.map(|fill| register_decal(fill, &mut procedural.materials)).transpose()?.flatten(); let height = layer.height_mask; let height_params = if height.enabled && mask_count != 0 { if !height.contrast.is_finite() || !height.offset.is_finite() { return Err("A layer's height mask has invalid parameters."); } [height.contrast.to_bits(), height.offset.to_bits()] } else { [0; 2] }; let first_op = operations.len(); let mut height_op = 0; for &(channel, _) in &set.channels { if mask_background == 0.0 && mask_count == 0 { break; } let Some(blend) = layer.blend(channel) else { continue }; if blend.mode == BlendMode::Disable || blend.opacity <= 0.0 { continue; } if !blend.opacity.is_finite() { return Err("A layer has an invalid opacity."); } let (painted, brush_value) = if fill.is_none() { (sparse_channel(pixels, layer.id, channel)?, brush.as_ref().and_then(|brush| brush.value_for_layer(layer.id, channel))) } else { (None, None) }; let content_start = if per_channel { effects.len() as u32 } else { shared_content }; let mut adds_coverage = false; for (effect, shared_stage, shared_template, channel_ops) in &templates { // A channel without a stage of its own keeps the placeholder, so an anchor's content cut holds on every channel let (stage, template) = match channel_ops.as_ref().and_then(|ops| ops.get(&channel)) { Some((channel_stage, op)) => (shared_stage.map(|placeholder| channel_stage.unwrap_or(placeholder)), Some(*op)), None => (*shared_stage, *shared_template), }; effects.extend(stage); let op = if let Some(op) = template { op } else if let Some(op) = content_deposit(effect, (channel, around), pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns))? { adds_coverage = true; op } else { Operation { ids: [0, NOOP_EFFECT_OPCODE, 0, 0], ..Operation::zeroed() } }; effects.push(op); } if fill.is_none() && painted.is_none() && brush_value.is_none() && !adds_coverage { if per_channel { effects.truncate(content_start as usize); } continue; } let content_count = effects.len() as u32 - content_start; let default = channel.default_value(); let source = fill.and_then(|fill| fill.sources.get(&channel)); if first_layer != 0 && source.is_some_and(|source| source.reads_anchor(None)) { return Err("The GPU layer stack reads across the CPU material boundary."); } let slot = channel_slot(channel); // Neutral fills can reset a channel only after its first contribution if !non_default[slot as usize] && painted.is_none() && brush_value.is_none() && content_count == 0 && matches!(blend.mode, BlendMode::Normal | BlendMode::Passthrough | BlendMode::Replace) && source.is_none_or(|source| matches!(source, Source::Uniform(value) if *value == default)) { continue; } non_default[slot as usize] = true; let mut op = if fill.is_none() { let carried = brush.as_ref().filter(|_| brush_value.is_some()).and_then(|brush| brush.carried_slot(channel)); content_paint(layer.id, channel, painted, brush_value, stencil_pigment, carried, &mut paint) } else { fill.and_then(|fill| source_operation(source, &placed(around, &fill.projection), fill.sampling, default, channel.kind(), &mut procedural)) .ok_or("A fill source or projection uses CPU compositing.")? }; if let Some(decal) = decal { op.uv[0] = decal as f32; } bind_tile_source(&mut op, source, &mut tile_patterns); op.ids[0] = slot; op.low[3] = blend.opacity.min(1.0); op.balance[1] = mask_background; op.balance[2] = blend_code(blend.mode) as f32; op.effects = [mask_start, mask_count, content_start, content_count]; op.spatial[3] = u32::from(adds_coverage); if height_params[0] != 0 && channel == Channel::Height { height_op = operations.len() as u32 + 1; } operations.push(op); } packages::order_layer_operations(&mut operations[first_op..]); if height_op != 0 { // The reorder can move the Height operation that the height mask reads let height = operations[first_op..].iter().position(|op| op.ids[0] == channel_slot(Channel::Height)); height_op = height.map_or(0, |index| (first_op + index) as u32 + 1); } for op in &mut operations[first_op..] { op.constraints = [geometry_mask, height_op, height_params[0], height_params[1]]; } if first_op != operations.len() { mask_layers.push((id, around, first_op as u32)); } else if mask.as_ref().is_some_and(|mask| { mask.effects.iter().any(|effect| effect.visible && (!effect.kind.anchors_read().is_empty() || matches!(effect.kind, EffectKind::Anchor))) }) { // A layer with no display channels can still publish anchors in its mask mask_layers.push((id, around, first_op as u32)); operations.push(Operation { ids: [u32::MAX, ANCHOR_PUBLISH_MASK, 0, 0], effects: [mask_start, mask_count, 0, 0], balance: [0.0, mask_background, 0.0, 0.0], constraints: [geometry_mask, 0, 0, 0], ..Operation::zeroed() }); } procedural.anchors.draw_ranges.push(first_op as u32..operations.len() as u32); if !content_anchors.is_empty() { let has_channels = set.channels.iter().any(|&(channel, _)| layer.blend(channel).is_some_and(|blend| blend.mode != BlendMode::Disable && blend.opacity > 0.0)); if !has_channels && mask.is_none_or(|mask| !mask.effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor))) { continue; } } for (anchor, cut) in content_anchors { let publication = procedural.anchors.publish(anchor, false); operations.push(Operation { ids: [u32::MAX, ANCHOR_PUBLISH_LAYER, publication, 0], effects: [first_op as u32, cut, 0, 0], ..Operation::zeroed() }); } } let mut display_outputs = display_bit(DisplayKind::BaseColor) | display_bit(DisplayKind::Orm); for channel in Channel::ALL.into_iter().take(Channel::SHADED_COUNT) { let slot = channel_slot(channel); if operations.iter().any(|op| { !groups::is_group(op) && op.ids[0] == slot && (op.ids[1] != 0 || op.low[..3] != channel.default_value() || op.effects[3] != 0 || op.balance[2] != 0.0) }) { display_outputs |= display_bit(DisplayKind::of_channel(channel)); } } groups.finish(&operations); let layer_count = operations.len() as u32; if !operations.iter().any(|op| op.constraints[0] != 0) { geometry.parts.clear(); } operations.extend(effects); bind_input_sources(&mut operations, layer_count, &procedural.input_sources); let mut filters = FilterPlan::compile(&mut operations, layer_count, &procedural); generator_p2::bind_sources(&mut procedural, operations.len() as u32); bind_generator_sources(&mut operations, &procedural.generator_sources); filters.bind_anchors(&mut operations); let udim = udim::bind(layout.as_ref(), &mut filters, &mut procedural).ok_or("The UV tile layout exceeds the GPU parameter table.")?; // A UV tile smaller than its block shades its height slopes at its own scale (Extra's alpha) if layout.as_ref().is_some_and(|layout| layout.scaled) { display_outputs |= display_bit(DisplayKind::Extra); } let region = filters.expand(region, project.texture_sets.get(ts).map_or((0, 0), texturecraft_core::TextureSet::size)); let (brush_alpha, brush_stencil, brush_carried) = brush.map_or((None, None, None), |brush| (Some(brush.alpha), brush.stencil, brush.carried)); let needs_surface = brush_stencil.is_some() || needs_surface(&operations); generator_p2::compile_captures(&mut procedural.micro, project, pixels, ts, remaining, brush_alpha.is_some())?; Ok(Self { underlay: None, operations, layer_count, filters, groups, geometry, paint: paint.images, ramp_words: procedural.ramp_words, curvature_sizes: procedural.curvature_sizes, tile_patterns, material_images: procedural.materials, brush_alpha, brush_stencil, brush_carried, region, coverage: None, surface: None, needs_surface, baked: None, id_bake: None, display_outputs, glossiness: set.has_channel(Channel::Glossiness), mix_baked_ao: set.ao_mixing == texturecraft_core::AoMixing::Multiply, mask_preview: false, mask_layer: 0, mask_layers, thumb: [0; 4], image_words: procedural.image_words, environment: LateEnvironment::new(procedural.environment_word, &project.display), bake_rows: procedural.bake_rows, udim, udim_layout: layout, p3b_fields: p3b::FieldPlan::new(procedural.p3b_fields, set.material), micro: procedural.micro, }) } /// Compose one layer's enabled mask into the standalone grayscale view. pub fn try_compile_mask_preview( project: &Project, pixels: &PixelStore, ts: usize, owner: LayerId, region: Option, brush: Option, ) -> Result { let set = project.texture_sets.get(ts).ok_or("The texture set is missing.")?; packages::check_set(set, true)?; // The folders around the requested layer (an instance's own, as the CPU places it) re-place its mask fills let requested = owner; let owner = project.mask_owner(owner); let around = project.contents_around(requested); let mask = project.layers.get(&owner).and_then(|layer| layer.mask.as_ref()).filter(|mask| mask.enabled); let mask = mask.ok_or("The layer has no enabled mask.")?; // A mask reading anchors or the layers needs the stack below it: the material program let reads_below = |effect: &Effect| { !effect.kind.anchors_read().is_empty() || effect.inputs.values().any(|source| source.reads_anchor(None)) || effect.kind.reads_stack() }; if mask.effects.iter().any(|effect| effect.visible && reads_below(effect)) { // The material program draws the owner once per placement: show the draw where the requested layer sits let mut program = Self::try_compile_with_brush(project, pixels, ts, region, brush)?; let draw = program.mask_layers.iter().rev().find(|&&(id, offset, _)| (id == requested || id == owner) && offset == around); program.mask_layer = draw.ok_or("The mask's GPU anchor stack is missing.")?.2; program.mask_preview = true; program.display_outputs = display_bit(DisplayKind::BaseColor); return Ok(program); } if let Some(brush) = &brush { brush.validate(set.size())?; } let mut operations = vec![Operation::zeroed()]; let mut paint = PaintInputs::default(); let mut procedural = ProceduralInputs::new(set.resolution); // P8: a UV tile atlas's block, its tile scales and the set's own resolution let layout = udim::UdimLayout::of(set); udim::prepare(layout.as_ref(), &mut procedural); let mut tile_patterns = TilePatterns::default(); let background = compile_mask(Some(mask), around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut operations)?; operations[0].effects[1] = operations.len() as u32 - 1; operations[0].balance[1] = background; bind_input_sources(&mut operations, 1, &procedural.input_sources); let mut filters = FilterPlan::compile(&mut operations, 1, &procedural); generator_p2::bind_sources(&mut procedural, operations.len() as u32); bind_generator_sources(&mut operations, &procedural.generator_sources); filters.bind_anchors(&mut operations); let udim = udim::bind(layout.as_ref(), &mut filters, &mut procedural).ok_or("The UV tile layout exceeds the GPU parameter table.")?; let region = filters.expand(region, project.texture_sets.get(ts).map_or((0, 0), texturecraft_core::TextureSet::size)); let (brush_alpha, brush_stencil, brush_carried) = brush.map_or((None, None, None), |brush| (Some(brush.alpha), brush.stencil, brush.carried)); let needs_surface = brush_stencil.is_some() || needs_surface(&operations); let mut remaining = generator_p2::MAX_CAPTURE_PROGRAMS; generator_p2::compile_captures(&mut procedural.micro, project, pixels, ts, &mut remaining, brush_alpha.is_some())?; Ok(Self { underlay: None, operations, layer_count: 1, filters, groups: GroupPlan::default(), geometry: GeometryMasks::default(), paint: paint.images, ramp_words: procedural.ramp_words, curvature_sizes: procedural.curvature_sizes, tile_patterns, material_images: procedural.materials, brush_alpha, brush_stencil, brush_carried, region, coverage: None, surface: None, needs_surface, baked: None, id_bake: None, // Reuse the first four-byte display slot for linear grayscale display_outputs: display_bit(DisplayKind::BaseColor), glossiness: false, mix_baked_ao: false, mask_preview: true, mask_layer: 0, mask_layers: Vec::new(), thumb: [0; 4], image_words: procedural.image_words, environment: LateEnvironment::new(procedural.environment_word, &project.display), bake_rows: procedural.bake_rows, udim, udim_layout: layout, p3b_fields: p3b::FieldPlan::new(procedural.p3b_fields, set.material), micro: procedural.micro, }) } } #[cfg(test)] mod tests { use crate::gpu_composite::*; use texturecraft_core::{Channel, TextureSet}; /// A thumbnail on a set with a baked normal map writes only its thumbnail, not the Normal map #[test] fn a_thumbnail_with_a_baked_normal_writes_only_the_thumbnail() { let mut project = Project::new("Thumbnail", "builtin:plane"); project.texture_sets.push(TextureSet::new("Plane", 0, 64)); let mesh = Arc::new(texturecraft_geom::primitives::plane(1.0, 1)); let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, 64, 64)); let baked = BakedMaps { resolution: 64, maps: BTreeMap::from([(BakedMap::Normal, Arc::new(vec![0.5; 64 * 64 * 3]))]) }; let mut program = CompositeProgram::try_compile_region(&project, &PixelStore::default(), 0, None).unwrap(); program.set_thumbnail(Channel::Roughness, false).unwrap(); program.set_surface_inputs(&mesh, &gbuf, Some(&baked)).unwrap(); assert!(program.writes_display(DisplayKind::BaseColor), "the thumbnail's own output"); assert!(!program.writes_display(DisplayKind::Normal), "no copy into the Normal map"); } }