mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-19 22:10:42 +01:00
Merge pull request #290 from Rebornim/feat/drop-on-hovered-set
Drop a shelf material on the texture set under the cursor
This commit is contained in:
9 files changed
+308
-37
No files matched your search
@@ -132,7 +132,7 @@ impl Session {
|
||||
fn material_files(&mut self, opts: ExportOptions, tiled: bool, materials: usize) -> Result<Vec<Vec<ExportedFile>>> {
|
||||
let opts = ExportOptions { atlas: true, ..opts };
|
||||
(0..materials)
|
||||
.map(|m| match self.doc.project.texture_sets.iter().position(|t| t.material == m) {
|
||||
.map(|m| match self.texture_set_of_material(m) {
|
||||
Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts),
|
||||
_ => Ok(Vec::new()),
|
||||
})
|
||||
|
||||
@@ -35,6 +35,16 @@ impl Session {
|
||||
pick(&ctx, screen)
|
||||
}
|
||||
|
||||
/// The texture set that paints mesh material `material` (a [`SurfaceHit::material`])
|
||||
pub fn texture_set_of_material(&self, material: usize) -> Option<usize> {
|
||||
self.doc.project.texture_sets.iter().position(|t| t.material == material)
|
||||
}
|
||||
|
||||
/// The texture set of the surface under viewport pixel `screen`
|
||||
pub fn texture_set_at(&self, screen: Vec2, viewport: Vec2) -> Option<usize> {
|
||||
self.pick(screen, viewport).and_then(|hit| self.texture_set_of_material(hit.material))
|
||||
}
|
||||
|
||||
/// Resolve what a stroke on the selected layer paints into, creating the mask paint effect
|
||||
/// when painting a mask. Must run inside the stroke's history snapshot.
|
||||
fn paint_target(&mut self) -> Result<PaintTarget> {
|
||||
@@ -560,7 +570,7 @@ impl Session {
|
||||
/// Color picker: copy the material under the cursor into the tool's paint values.
|
||||
pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result<BTreeMap<Channel, [f32; 3]>> {
|
||||
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
let ts = self.doc.project.texture_sets.iter().position(|t| t.material == hit.material).unwrap_or(self.ts());
|
||||
let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts());
|
||||
let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
let (w, h) = (cache.size.0 as f32, cache.size.1 as f32);
|
||||
let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32);
|
||||
|
||||
@@ -23,8 +23,10 @@ pub mod ibl;
|
||||
pub mod mesh_maps;
|
||||
pub mod readback;
|
||||
pub mod renderer;
|
||||
pub mod set_highlight;
|
||||
mod subdivide;
|
||||
pub mod trace;
|
||||
|
||||
pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale};
|
||||
pub use set_highlight::SetHighlight;
|
||||
pub use wgpu;
|
||||
@@ -32,6 +32,7 @@ use texturecraft_texel::TILE;
|
||||
|
||||
use crate::gpu_trace::{Checked, checked};
|
||||
use crate::ibl;
|
||||
use crate::set_highlight::SetHighlight;
|
||||
use crate::subdivide::{self, Vertex};
|
||||
|
||||
pub const MSAA: u32 = 4;
|
||||
@@ -76,6 +77,8 @@ struct GlobalsRaw {
|
||||
fwd: [f32; 4],
|
||||
disp: [f32; 4],
|
||||
refr: [f32; 4],
|
||||
highlight: [f32; 4],
|
||||
highlight_shift: [f32; 4],
|
||||
}
|
||||
|
||||
/// The post pass uniform (see `Post` in post.wgsl).
|
||||
@@ -96,6 +99,15 @@ struct BlitRaw {
|
||||
dst: [f32; 4],
|
||||
}
|
||||
|
||||
/// Width of the highlighted set's edge lines, in pixels
|
||||
const HIGHLIGHT_WIDTH_PX: f32 = 1.5;
|
||||
|
||||
/// Opacity of the highlighted set's edge lines
|
||||
const HIGHLIGHT_OPACITY: f32 = 0.9;
|
||||
|
||||
/// Copies of each highlight line, shifted diagonally to the four corners of its extra width (`vs_wire_highlight`)
|
||||
const HIGHLIGHT_SHIFTS: u32 = 4;
|
||||
|
||||
/// How the material is shaded (from the project's display settings and the view mode).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Shade {
|
||||
@@ -134,6 +146,8 @@ pub struct Shade {
|
||||
pub grain: f32,
|
||||
/// Draw the mesh edges over the shaded 3D view (depth tested).
|
||||
pub wireframe_3d: bool,
|
||||
/// One texture set's mesh edges in a highlight color over the 3D view (the set under a shelf drag)
|
||||
pub highlight: Option<SetHighlight>,
|
||||
/// Specular/glossiness shading: base color is the diffuse color and the Specular channel the
|
||||
/// F0 color (roughness arrives as 1 - glossiness from the display conversion).
|
||||
pub spec_gloss: bool,
|
||||
@@ -235,6 +249,7 @@ impl Default for Shade {
|
||||
sharpen: 0.0,
|
||||
grain: 0.0,
|
||||
wireframe_3d: false,
|
||||
highlight: None,
|
||||
spec_gloss: false,
|
||||
parallax: false,
|
||||
taa: false,
|
||||
@@ -513,6 +528,8 @@ pub struct Renderer {
|
||||
uv_pipeline: wgpu::RenderPipeline,
|
||||
wire_pipeline: wgpu::RenderPipeline,
|
||||
wire3d_pipeline: wgpu::RenderPipeline,
|
||||
/// The highlighted set's mesh edges, wider and in the highlight color
|
||||
highlight_pipeline: wgpu::RenderPipeline,
|
||||
bg_pipeline: wgpu::RenderPipeline,
|
||||
blit_pipeline: wgpu::RenderPipeline,
|
||||
post_pipeline: wgpu::RenderPipeline,
|
||||
@@ -886,7 +903,9 @@ impl Renderer {
|
||||
let blend = Some(wgpu::BlendState::ALPHA_BLENDING);
|
||||
let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always());
|
||||
let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual));
|
||||
let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth);
|
||||
let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone());
|
||||
let highlight_pipeline =
|
||||
pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth);
|
||||
let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always());
|
||||
let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None);
|
||||
let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None);
|
||||
@@ -994,6 +1013,7 @@ impl Renderer {
|
||||
uv_pipeline,
|
||||
wire_pipeline,
|
||||
wire3d_pipeline,
|
||||
highlight_pipeline,
|
||||
bg_pipeline,
|
||||
blit_pipeline,
|
||||
post_pipeline,
|
||||
@@ -1531,13 +1551,7 @@ impl Renderer {
|
||||
visible: &'a [bool],
|
||||
only: Option<usize>,
|
||||
) -> impl Iterator<Item = (std::ops::Range<u32>, &'a SetGpu)> + 'a {
|
||||
ranges.iter().filter_map(move |&(start, count, material)| {
|
||||
let ts = self.material_sets.get(material).copied().flatten()?;
|
||||
if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
Some((start..start + count, self.sets.get(ts)?))
|
||||
})
|
||||
drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, ts)| Some((range, self.sets.get(ts)?)))
|
||||
}
|
||||
|
||||
/// Keep the key-light shadow map current; returns its view-projection. `light` points to
|
||||
@@ -1707,6 +1721,8 @@ impl Renderer {
|
||||
fwd: [fwd.x, fwd.y, fwd.z, 0.0],
|
||||
disp,
|
||||
refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0],
|
||||
highlight: highlight_globals(s, data),
|
||||
highlight_shift: highlight_shift(frame.size),
|
||||
};
|
||||
let flag = |b: bool| if b { 1.0 } else { 0.0 };
|
||||
let post = PostRaw {
|
||||
@@ -1805,7 +1821,7 @@ impl Renderer {
|
||||
|
||||
/// The scene without transmissive surfaces into `b` (MSAA resolved into mip 0), then its mips.
|
||||
fn behind_pass(&self, encoder: &mut wgpu::CommandEncoder, v: &ViewTargets, b: &Behind, globals_bg: &wgpu::BindGroup, frame: &Frame) {
|
||||
self.draw_scene(encoder, v, &b.level0, globals_bg, frame, &self.opaque_pipeline, None, &self.refr_black);
|
||||
self.draw_scene(encoder, v, &b.level0, globals_bg, frame, &self.opaque_pipeline, None, None, &self.refr_black);
|
||||
let Some(pipe) = self.mip_pipelines.get(&self.hdr_format) else { return };
|
||||
for (dst, bg) in &b.mips {
|
||||
fullscreen(encoder, "tc_behind_mip", dst, CLEAR, pipe, bg);
|
||||
@@ -1869,10 +1885,11 @@ impl Renderer {
|
||||
};
|
||||
// Transmissive surfaces refract what the behind pass rendered this frame.
|
||||
let refr = v.behind.as_ref().filter(|_| frame.shade.refraction).map_or(&self.refr_black, |b| &b.bg);
|
||||
self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, refr);
|
||||
let highlight = frame.shade.highlight.filter(|_| uv_ts.is_none()).map(|highlight| (&self.highlight_pipeline, highlight.set));
|
||||
self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr);
|
||||
}
|
||||
|
||||
/// One scene pass: background, then the mesh with `pipe` and the wireframe with `wire`.
|
||||
/// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight`
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_scene(
|
||||
&self,
|
||||
@@ -1883,6 +1900,7 @@ impl Renderer {
|
||||
frame: &Frame,
|
||||
pipe: &wgpu::RenderPipeline,
|
||||
wire: Option<&wgpu::RenderPipeline>,
|
||||
highlight: Option<(&wgpu::RenderPipeline, usize)>,
|
||||
refr: &wgpu::BindGroup,
|
||||
) {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
@@ -1912,15 +1930,21 @@ impl Renderer {
|
||||
};
|
||||
pass.set_bind_group(2, refr, &[]);
|
||||
let geo = self.geometry(m, frame);
|
||||
// The wireframe draws the mesh's own edges (displaced in the vertex shader too).
|
||||
for (pipe, vb, ib, ranges) in [(Some(pipe), &geo.vb, &geo.ib, &geo.draws), (wire, &m.geo.vb, &m.lines, &m.line_draws)] {
|
||||
// The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too)
|
||||
let (highlight, highlight_set) = highlight.unzip();
|
||||
let passes = [
|
||||
(Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1),
|
||||
(wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1),
|
||||
(highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS),
|
||||
];
|
||||
for (pipe, vb, ib, ranges, only, instances) in passes {
|
||||
let Some(pipe) = pipe else { continue };
|
||||
pass.set_pipeline(pipe);
|
||||
pass.set_vertex_buffer(0, vb.slice(..));
|
||||
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(ranges, &frame.visible, uv_ts) {
|
||||
for (range, set) in self.drawable(ranges, &frame.visible, only) {
|
||||
pass.set_bind_group(1, &set.bind_group, &[]);
|
||||
pass.draw_indexed(range, 0, 0..1);
|
||||
pass.draw_indexed(range, 0, 0..instances);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1963,6 +1987,39 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Index ranges of `ranges` (first, count, material) whose texture set (from `material_sets`) is visible and is `only`, when given, with that set's index
|
||||
fn drawable_ranges<'a>(
|
||||
ranges: &'a [(u32, u32, usize)],
|
||||
material_sets: &'a [Option<usize>],
|
||||
visible: &'a [bool],
|
||||
only: Option<usize>,
|
||||
) -> impl Iterator<Item = (std::ops::Range<u32>, usize)> + 'a {
|
||||
ranges.iter().filter_map(move |&(start, count, material)| {
|
||||
let ts = material_sets.get(material).copied().flatten()?;
|
||||
if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((start..start + count, ts))
|
||||
})
|
||||
}
|
||||
|
||||
/// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is
|
||||
fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] {
|
||||
let Some(highlight) = shade.highlight else { return [0.0; 4] };
|
||||
|
||||
let [r, g, b] = if data { highlight.color } else { highlight.scene_color(shade.exposure_ev, shade.aces) };
|
||||
[r, g, b, HIGHLIGHT_OPACITY]
|
||||
}
|
||||
|
||||
/// Globals `highlight_shift`: how far each of the highlight's line copies moves sideways, in clip units of a `size` pixel target
|
||||
fn highlight_shift(size: [u32; 2]) -> [f32; 4] {
|
||||
let half_extra_width = (HIGHLIGHT_WIDTH_PX - 1.0) * 0.5;
|
||||
let clip_per_pixel = size.map(|pixels| 2.0 / pixels.max(1) as f32);
|
||||
|
||||
[half_extra_width * clip_per_pixel[0], half_extra_width * clip_per_pixel[1], 0.0, 0.0]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -2026,6 +2083,25 @@ mod tests {
|
||||
assert!(!h.renderer.awaiting_gpu());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_highlight_draws_only_the_highlighted_sets_edges() {
|
||||
let line_draws = [(0, 4, 0), (4, 6, 1), (10, 2, 2)];
|
||||
let material_sets = [Some(0), Some(1), Some(2)];
|
||||
let highlighted = |visible: &[bool]| drawable_ranges(&line_draws, &material_sets, visible, Some(1)).collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(highlighted(&[true; 3]), vec![(4..10, 1)]);
|
||||
assert_eq!(highlighted(&[true, false, true]), vec![], "a hidden set shows no highlight");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_data_view_takes_the_highlight_color_as_it_is() {
|
||||
let color = [0.8, 0.25, 0.08];
|
||||
let shade = Shade { highlight: Some(SetHighlight { set: 0, color }), exposure_ev: 1.0, ..Shade::default() };
|
||||
|
||||
assert_eq!(highlight_globals(&shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]);
|
||||
assert_ne!(highlight_globals(&shade, false)[..3], color, "the material view undoes exposure and tone mapping");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verdict_that_never_comes_counts_as_a_failure() {
|
||||
let Some((mut h, tx)) = awaiting() else { return };
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! A texture set's mesh edges drawn over the 3D view in a highlight color (the set under a shelf drag)
|
||||
|
||||
/// Brightest on-screen value the tone curve can reach without an infinite scene value
|
||||
const MAX_ACES_SCREEN_VALUE: f32 = 0.99;
|
||||
|
||||
/// Scene scale the post pass applies before its ACES curve (`aces` in post.wgsl)
|
||||
const ACES_INPUT_SCALE: f32 = 0.6;
|
||||
|
||||
/// Draw texture set `set`'s mesh edges over the 3D view in `color`
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SetHighlight {
|
||||
pub set: usize,
|
||||
/// The lines' color on screen, linear RGB
|
||||
pub color: [f32; 3],
|
||||
}
|
||||
|
||||
impl SetHighlight {
|
||||
/// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`]
|
||||
pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] {
|
||||
let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE);
|
||||
|
||||
self.color.map(|screen| {
|
||||
let screen = screen.max(0.0);
|
||||
let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen };
|
||||
|
||||
exposed / exposure
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The input of post.wgsl's `aces` that gives `screen`: the positive root of its rational curve solved for the input
|
||||
fn inverse_aces(screen: f32) -> f32 {
|
||||
let (a, b, c) = (2.43 * screen - 2.51, 0.59 * screen - 0.03, 0.14 * screen);
|
||||
let scaled = (-b - (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a);
|
||||
|
||||
scaled / ACES_INPUT_SCALE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// post.wgsl's `aces` with exposure `exposure_ev`
|
||||
fn tone_mapped(scene: f32, exposure_ev: f32) -> f32 {
|
||||
let v = scene * 2f32.powf(exposure_ev) * ACES_INPUT_SCALE;
|
||||
((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scene_color_shows_the_highlight_color_on_screen() {
|
||||
let highlight = SetHighlight { set: 0, color: [0.9, 0.3, 0.05] };
|
||||
for exposure_ev in [-2.0, 0.0, 1.5] {
|
||||
let scene = highlight.scene_color(exposure_ev, true);
|
||||
for (scene, screen) in scene.iter().zip(highlight.color) {
|
||||
assert!((tone_mapped(*scene, exposure_ev) - screen).abs() < 1e-4, "{exposure_ev} EV: {scene} → {screen}");
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(highlight.scene_color(1.0, false), [0.45, 0.15, 0.025], "linear: exposure only");
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ struct Globals {
|
||||
fwd: vec4<f32>, // xyz camera view direction (unit), w -
|
||||
disp: vec4<f32>, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w -
|
||||
refr: vec4<f32>, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w -
|
||||
highlight: vec4<f32>, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity
|
||||
highlight_shift: vec4<f32>, // xy sideways shift of each highlight line copy (clip units), zw -
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> g: Globals;
|
||||
@@ -659,8 +661,7 @@ fn fs_wire(i: VOut) -> @location(0) vec4<f32> {
|
||||
|
||||
// 3D wireframe over the shaded mesh: depth-tested, pulled slightly toward the camera so the
|
||||
// lines win against their own triangles.
|
||||
@vertex
|
||||
fn vs_wire3d(v: VIn) -> VOut {
|
||||
fn wire3d(v: VIn) -> VOut {
|
||||
var o: VOut;
|
||||
o.wpos = v.pos;
|
||||
o.nrm = v.nrm;
|
||||
@@ -671,7 +672,26 @@ fn vs_wire3d(v: VIn) -> VOut {
|
||||
return o;
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_wire3d(v: VIn) -> VOut {
|
||||
return wire3d(v);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_wire3d(i: VOut) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(0.35, 0.35, 0.35, 0.45);
|
||||
}
|
||||
|
||||
// The highlighted set's edges: four copies of each line, shifted to the corners of the extra width, make it wider than one pixel
|
||||
@vertex
|
||||
fn vs_wire_highlight(v: VIn, @builtin(instance_index) copy: u32) -> VOut {
|
||||
var o = wire3d(v);
|
||||
let corner = vec2<f32>(f32(copy & 1u), f32((copy >> 1u) & 1u)) * 2.0 - 1.0;
|
||||
o.clip = vec4<f32>(o.clip.xy + corner * g.highlight_shift.xy * o.clip.w, o.clip.zw);
|
||||
return o;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_wire_highlight(i: VOut) -> @location(0) vec4<f32> {
|
||||
return g.highlight;
|
||||
}
|
||||
+37
-15
@@ -11,6 +11,7 @@ use texturecraft_engine::core::ProceduralKind;
|
||||
use texturecraft_engine::filter_lib::FILTERS;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use texturecraft_engine::formats::mcmat::MCMAT_EXT;
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::materials::MATERIALS;
|
||||
use texturecraft_engine::paint::alphas;
|
||||
use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
|
||||
@@ -119,11 +120,27 @@ pub enum DropZone {
|
||||
Brush,
|
||||
/// The 2D view: alphas and materials.
|
||||
View2d,
|
||||
/// The 3D view: alphas, materials and textures (placed as decals where they drop).
|
||||
/// The 3D view: alphas, materials (on the texture set they drop on) and textures (placed as decals where they drop).
|
||||
View3d,
|
||||
}
|
||||
|
||||
/// Highlight accepted shelf assets on hover and apply them on drop
|
||||
/// The texture set under the pointer while a shelf material is dragged over the 3D view `response`: the set a drop there applies it to
|
||||
pub fn material_drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option<usize> {
|
||||
if app.ui.mode != crate::state::Mode::Painting {
|
||||
return None;
|
||||
}
|
||||
|
||||
response.dnd_hover_payload::<ShelfDrag>().filter(|drag| drag.asset.is_material())?;
|
||||
set_under_pointer(app, ui, response)
|
||||
}
|
||||
|
||||
/// The texture set of the surface under the pointer in the 3D view `response`
|
||||
fn set_under_pointer(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option<usize> {
|
||||
let local_position = ui.input(|input| input.pointer.interact_pos())? - response.rect.min;
|
||||
app.session.texture_set_at(Vec2::new(local_position.x, local_position.y), app.session.viewport)
|
||||
}
|
||||
|
||||
/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material goes to the texture set under the pointer, highlighted by the view itself ([`material_drop_set`])
|
||||
pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, zone: DropZone) {
|
||||
if app.ui.mode != crate::state::Mode::Painting {
|
||||
return;
|
||||
@@ -136,23 +153,28 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response
|
||||
Asset::Texture(_) => zone == DropZone::View3d,
|
||||
Asset::SmartMask(_) | Asset::Filter(_) => false,
|
||||
};
|
||||
if response.dnd_hover_payload::<ShelfDrag>().is_some_and(|drag| accepts(&drag)) {
|
||||
let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.is_material();
|
||||
if response.dnd_hover_payload::<ShelfDrag>().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) {
|
||||
ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
let pointer = ui.input(|input| input.pointer.interact_pos());
|
||||
if let Some(drag) = dnd_release::<ShelfDrag>(response)
|
||||
&& accepts(&drag)
|
||||
{
|
||||
match (&drag.asset, pointer) {
|
||||
(Asset::Texture(name), Some(position)) => {
|
||||
let (local_position, viewport_size) = (position - response.rect.min, response.rect.size());
|
||||
app.run(
|
||||
"layer.add.decal",
|
||||
json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]}),
|
||||
);
|
||||
}
|
||||
(asset, _) => apply(app, asset),
|
||||
let Some(drag) = dnd_release::<ShelfDrag>(response).filter(|drag| accepts(drag)) else { return };
|
||||
|
||||
match (&drag.asset, pointer) {
|
||||
(Asset::Texture(name), Some(position)) => {
|
||||
let (local_position, viewport_size) = (position - response.rect.min, response.rect.size());
|
||||
app.run("layer.add.decal", json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]}));
|
||||
}
|
||||
// The background takes nothing
|
||||
(asset, _) if onto_set(asset) => {
|
||||
let Some(ts) = set_under_pointer(app, ui, response) else { return };
|
||||
|
||||
if app.run("textureSet.select", json!({"ts": ts})).is_some() {
|
||||
apply(app, asset);
|
||||
}
|
||||
}
|
||||
(asset, _) => apply(app, asset),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use texturecraft_engine::camera_cmds::DEFAULT_CAMERA;
|
||||
use texturecraft_engine::core::{BakedMap, Channel};
|
||||
use texturecraft_engine::geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_engine::{Tool, ViewMode};
|
||||
use texturecraft_render::{Frame, Shade, ViewKind};
|
||||
use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::gpu::ViewCallback;
|
||||
@@ -217,6 +217,14 @@ fn shade(app: &TextureCraftApp) -> Shade {
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture set a shelf material dragged over the 3D view `response` would drop on, its edges drawn in the accent color
|
||||
fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option<SetHighlight> {
|
||||
let set = crate::shelf::material_drop_set(app, ui, response)?;
|
||||
let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent);
|
||||
|
||||
Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] })
|
||||
}
|
||||
|
||||
/// Show what the GPU side reported (each message once while its toast is up).
|
||||
fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) {
|
||||
let names: Vec<String> = reports.memory.iter().filter_map(|ts| app.session.doc.project.texture_sets.get(*ts).map(|t| t.name.clone())).collect();
|
||||
@@ -565,11 +573,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
size: frame_size_in_pixels(ui, rect),
|
||||
kind: ViewKind::Scene,
|
||||
camera: app.session.camera,
|
||||
shade: shade(app),
|
||||
shade: Shade { highlight: drop_highlight(app, ui, &resp), ..shade(app) },
|
||||
visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(),
|
||||
};
|
||||
add_callback(app, ui, rect, frame, sync);
|
||||
// Shelf drops: a material goes above the selection, an alpha on the brush.
|
||||
// Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush
|
||||
crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View3d);
|
||||
|
||||
// Brush cursor.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! A shelf material dropped on the 3D view goes to the texture set under the pointer
|
||||
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2};
|
||||
use egui_kittest::Harness;
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::shelf::{Asset, ShelfDrag};
|
||||
|
||||
/// Distance between the view points searched for a set or the background
|
||||
const SEARCH_STEP: f32 = 8.0;
|
||||
|
||||
/// The sample project (Ball = set 0, Base = set 1) with the Ball selected, at 1600 x 960
|
||||
fn sample_app() -> Harness<'static, TextureCraftApp> {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
harness.run_steps(4);
|
||||
assert_eq!(harness.state().session.ts(), 0);
|
||||
harness
|
||||
}
|
||||
|
||||
/// The first point of the 3D view showing texture set `set`, or the background when `None`
|
||||
fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option<usize>) -> Pos2 {
|
||||
let app = harness.state();
|
||||
let rect = app.viewport_rect;
|
||||
let steps = |length: f32| (1..(length / SEARCH_STEP) as usize).map(|step| step as f32 * SEARCH_STEP);
|
||||
|
||||
steps(rect.height())
|
||||
.flat_map(|y| steps(rect.width()).map(move |x| (x, y)))
|
||||
.find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set)
|
||||
.map(|(x, y)| rect.min + egui::vec2(x, y))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Drop a built-in shelf material at `position`, as a drag from the shelf ends there
|
||||
fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) {
|
||||
egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Material("iron_rusted"), label: "Iron".into() });
|
||||
harness.hover_at(position);
|
||||
harness.run_steps(2);
|
||||
|
||||
harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.run_steps(2);
|
||||
}
|
||||
|
||||
/// Top-level layer count of each texture set
|
||||
fn stack_sizes(harness: &Harness<'_, TextureCraftApp>) -> Vec<usize> {
|
||||
harness.state().session.doc.project.texture_sets.iter().map(|set| set.stack.len()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_material_dropped_on_another_set_goes_to_that_set_and_selects_it() {
|
||||
let mut harness = sample_app();
|
||||
let before = stack_sizes(&harness);
|
||||
|
||||
let base = point_over(&harness, Some(1));
|
||||
drop_material(&mut harness, base);
|
||||
|
||||
assert_eq!(harness.state().session.ts(), 1, "the set under the pointer is selected");
|
||||
assert_eq!(stack_sizes(&harness), vec![before[0], before[1] + 1], "only the set under the pointer gets the material");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_material_dropped_on_the_background_changes_nothing() {
|
||||
let mut harness = sample_app();
|
||||
let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len());
|
||||
|
||||
let background = point_over(&harness, None);
|
||||
drop_material(&mut harness, background);
|
||||
|
||||
assert_eq!(harness.state().session.ts(), 0);
|
||||
assert_eq!(stack_sizes(&harness), stacks);
|
||||
assert_eq!(harness.state().session.history_labels().len(), history);
|
||||
}
|
||||
Reference in new issue
Block a user