diff --git a/assets/i18n/en_US.json b/assets/i18n/en_US.json index d7b4256..63ef496 100644 --- a/assets/i18n/en_US.json +++ b/assets/i18n/en_US.json @@ -55,6 +55,8 @@ "account.storage_unavailable": "Storage unavailable", "account.the_server_did_not_sign_out": "The server did not sign out.", "account.use_https_or_http_on_localhost_for_development": "Use HTTPS, or HTTP on localhost for development.", + "app.show_or_hide_the_printer_or_tool_volume": "Show or hide the reference volume", + "app.the_model_is_outside_the_printer_or_tool_volume": "The model extends beyond the reference volume.", "agent_link.activity.batch": "Applying a batch of changes", "agent_link.activity.checking": "Checking the model", "agent_link.activity.creating": "Creating geometry", @@ -1350,6 +1352,7 @@ "realtime.websocket_disconnected_2": "WebSocket disconnected: {e}", "realtime.websocket_host_missing": "WebSocket host missing", "realtime.websocket_unavailable": "WebSocket unavailable", + "reference_volume.show": "Show reference volume", "release_notes.format": "•", "release_notes.latest": " · Latest", "release_notes.newer": "Newer", @@ -1472,6 +1475,12 @@ "router.suspended": "Routing on edge #{id} suspended: {error}", "router.width": "Width", "section_gizmo.drag_section_along_its_axis_esc_to_cancel": "Drag section {} along its axis · Esc to cancel. When viewed along the axis, drag up/down.", + "settings.printer_and_tool_volume": "Reference volume", + "settings.a_locked_reference_box_for_a_printer_s_build": "A fixed reference box for checking whether objects fit within a chosen space.", + "settings.width_x": "Width (X)", + "settings.depth_y": "Depth (Y)", + "settings.height_z": "Height (Z)", + "settings.clear_the_toggle_shortcut": "Clear the reference volume shortcut.", "settings.adjust_mouse_and_trackpad_navigation_sensitivity": "Adjust mouse and trackpad navigation sensitivity.", "settings.automatically_group_new_shapes": "Automatically group new shapes", "settings.automatically_size_grid_when_zooming": "Automatically size grid when zooming", @@ -1519,6 +1528,7 @@ "settings.snap_to_grid": "Snap to grid", "settings.spacing_controls_both_grid_lines_and_grid_snapping": "Spacing controls both grid lines and grid snapping. Every fifth line is emphasized.", "settings.system": "System", + "settings.toggle_reference_volume": "Toggle reference volume", "settings.tool": "Tool", "settings.tools": "Tools", "settings.tools_for_checking_performance_and_troubleshooting": "Tools for checking performance and troubleshooting.", diff --git a/assets/i18n/es_419.json b/assets/i18n/es_419.json index 0dc8717..488b332 100644 --- a/assets/i18n/es_419.json +++ b/assets/i18n/es_419.json @@ -55,6 +55,8 @@ "account.storage_unavailable": "Almacenamiento no disponible", "account.the_server_did_not_sign_out": "El servidor no cerró la sesión.", "account.use_https_or_http_on_localhost_for_development": "Usa HTTPS, o HTTP en localhost para desarrollo.", + "app.show_or_hide_the_printer_or_tool_volume": "Mostrar u ocultar el volumen de referencia", + "app.the_model_is_outside_the_printer_or_tool_volume": "El modelo se extiende más allá del volumen de referencia.", "agent_link.activity.batch": "Aplicando un lote de cambios", "agent_link.activity.checking": "Revisando el modelo", "agent_link.activity.creating": "Creando geometría", @@ -1345,6 +1347,7 @@ "realtime.websocket_disconnected_2": "WebSocket desconectado: {e}", "realtime.websocket_host_missing": "Falta el host de WebSocket", "realtime.websocket_unavailable": "WebSocket no disponible", + "reference_volume.show": "Mostrar volumen de referencia", "release_notes.format": "•", "release_notes.latest": " · Última", "release_notes.newer": "Más recientes", @@ -1467,6 +1470,12 @@ "router.suspended": "Fresado de la arista #{id} suspendido: {error}", "router.width": "Ancho", "section_gizmo.drag_section_along_its_axis_esc_to_cancel": "Arrastra la sección {} a lo largo de su eje · Esc para cancelar. Si se ve a lo largo del eje, arrastra hacia arriba/abajo.", + "settings.printer_and_tool_volume": "Volumen de referencia", + "settings.a_locked_reference_box_for_a_printer_s_build": "Una caja de referencia fija para comprobar si los objetos caben en un espacio definido.", + "settings.width_x": "Ancho (X)", + "settings.depth_y": "Profundidad (Y)", + "settings.height_z": "Altura (Z)", + "settings.clear_the_toggle_shortcut": "Borrar el atajo de volumen de referencia.", "settings.adjust_mouse_and_trackpad_navigation_sensitivity": "Ajusta la sensibilidad de la navegación con el mouse y el trackpad.", "settings.automatically_group_new_shapes": "Agrupar automáticamente las formas nuevas", "settings.automatically_size_grid_when_zooming": "Ajustar automáticamente el tamaño de la cuadrícula al hacer zoom", @@ -1514,6 +1523,7 @@ "settings.snap_to_grid": "Ajustar a la cuadrícula", "settings.spacing_controls_both_grid_lines_and_grid_snapping": "El espaciado controla tanto las líneas de la cuadrícula como el ajuste a la cuadrícula. Cada quinta línea aparece resaltada.", "settings.system": "Sistema", + "settings.toggle_reference_volume": "Alternar volumen de referencia", "settings.tool": "Herramienta", "settings.tools": "Herramientas", "settings.tools_for_checking_performance_and_troubleshooting": "Herramientas para comprobar el rendimiento y solucionar problemas.", diff --git a/assets/i18n/it_IT.json b/assets/i18n/it_IT.json index e7c7428..078f3b1 100644 --- a/assets/i18n/it_IT.json +++ b/assets/i18n/it_IT.json @@ -55,6 +55,8 @@ "account.storage_unavailable": "Archiviazione non disponibile", "account.the_server_did_not_sign_out": "Il server non ha effettuato la disconnessione.", "account.use_https_or_http_on_localhost_for_development": "Usa HTTPS, oppure HTTP su localhost per lo sviluppo.", + "app.show_or_hide_the_printer_or_tool_volume": "Mostra o nascondi il volume di riferimento", + "app.the_model_is_outside_the_printer_or_tool_volume": "Il modello si estende oltre il volume di riferimento.", "agent_link.activity.batch": "Applicazione di un gruppo di modifiche", "agent_link.activity.checking": "Verifica del modello", "agent_link.activity.creating": "Creazione della geometria", @@ -1350,6 +1352,7 @@ "realtime.websocket_disconnected_2": "WebSocket disconnesso: {e}", "realtime.websocket_host_missing": "Host WebSocket mancante", "realtime.websocket_unavailable": "WebSocket non disponibile", + "reference_volume.show": "Mostra volume di riferimento", "release_notes.format": "•", "release_notes.latest": " · Ultima", "release_notes.newer": "Più recenti", @@ -1472,6 +1475,12 @@ "router.suspended": "Fresatura sullo spigolo #{id} sospesa: {error}", "router.width": "Larghezza", "section_gizmo.drag_section_along_its_axis_esc_to_cancel": "Trascina la sezione {} lungo il suo asse · Esc per annullare. Se visto lungo l'asse, trascina su/giù.", + "settings.printer_and_tool_volume": "Volume di riferimento", + "settings.a_locked_reference_box_for_a_printer_s_build": "Un riquadro di riferimento fisso per verificare se gli oggetti rientrano in uno spazio definito.", + "settings.width_x": "Larghezza (X)", + "settings.depth_y": "Profondità (Y)", + "settings.height_z": "Altezza (Z)", + "settings.clear_the_toggle_shortcut": "Cancella la scorciatoia del volume di riferimento.", "settings.adjust_mouse_and_trackpad_navigation_sensitivity": "Regola la sensibilità di navigazione di mouse e trackpad.", "settings.automatically_group_new_shapes": "Raggruppa automaticamente le nuove forme", "settings.automatically_size_grid_when_zooming": "Ridimensiona automaticamente la griglia con lo zoom", @@ -1519,6 +1528,7 @@ "settings.snap_to_grid": "Aggancia alla griglia", "settings.spacing_controls_both_grid_lines_and_grid_snapping": "La spaziatura controlla sia le linee della griglia sia l'aggancio. Ogni quinta linea è evidenziata.", "settings.system": "Sistema", + "settings.toggle_reference_volume": "Attiva/disattiva volume di riferimento", "settings.tool": "Strumento", "settings.tools": "Strumenti", "settings.tools_for_checking_performance_and_troubleshooting": "Strumenti per controllare le prestazioni e risolvere i problemi.", diff --git a/assets/i18n/pt_BR.json b/assets/i18n/pt_BR.json index 5406d62..0912ee6 100644 --- a/assets/i18n/pt_BR.json +++ b/assets/i18n/pt_BR.json @@ -55,6 +55,8 @@ "account.storage_unavailable": "Armazenamento indisponível", "account.the_server_did_not_sign_out": "O servidor não encerrou a sessão.", "account.use_https_or_http_on_localhost_for_development": "Use HTTPS, ou HTTP no localhost para desenvolvimento.", + "app.show_or_hide_the_printer_or_tool_volume": "Mostrar ou ocultar o volume de referência", + "app.the_model_is_outside_the_printer_or_tool_volume": "O modelo ultrapassa o volume de referência.", "agent_link.activity.batch": "Aplicando um lote de alterações", "agent_link.activity.checking": "Verificando o modelo", "agent_link.activity.creating": "Criando geometria", @@ -1348,6 +1350,7 @@ "realtime.websocket_disconnected_2": "WebSocket desconectado: {e}", "realtime.websocket_host_missing": "Host do WebSocket ausente", "realtime.websocket_unavailable": "WebSocket indisponível", + "reference_volume.show": "Mostrar volume de referência", "release_notes.format": "•", "release_notes.latest": " · Mais recente", "release_notes.newer": "Mais nova", @@ -1470,6 +1473,12 @@ "router.suspended": "Tupia na aresta #{id} suspensa: {error}", "router.width": "Largura", "section_gizmo.drag_section_along_its_axis_esc_to_cancel": "Arraste a seção {} ao longo do eixo · Esc para cancelar. Quando visto ao longo do eixo, arraste para cima/baixo.", + "settings.printer_and_tool_volume": "Volume de referência", + "settings.a_locked_reference_box_for_a_printer_s_build": "Uma caixa de referência fixa para verificar se os objetos cabem em um espaço definido.", + "settings.width_x": "Largura (X)", + "settings.depth_y": "Profundidade (Y)", + "settings.height_z": "Altura (Z)", + "settings.clear_the_toggle_shortcut": "Limpar o atalho do volume de referência.", "settings.adjust_mouse_and_trackpad_navigation_sensitivity": "Ajuste a sensibilidade de navegação do mouse e do trackpad.", "settings.automatically_group_new_shapes": "Agrupar novas formas automaticamente", "settings.automatically_size_grid_when_zooming": "Ajustar o tamanho da grade automaticamente ao dar zoom", @@ -1517,6 +1526,7 @@ "settings.snap_to_grid": "Encaixar na grade", "settings.spacing_controls_both_grid_lines_and_grid_snapping": "O espaçamento controla as linhas da grade e o encaixe automático na grade. A cada cinco linhas, uma é destacada.", "settings.system": "Sistema", + "settings.toggle_reference_volume": "Alternar volume de referência", "settings.tool": "Ferramenta", "settings.tools": "Ferramentas", "settings.tools_for_checking_performance_and_troubleshooting": "Ferramentas para verificar o desempenho e solucionar problemas.", diff --git a/assets/i18n/vi_VN.json b/assets/i18n/vi_VN.json index 98126f3..47a4e47 100644 --- a/assets/i18n/vi_VN.json +++ b/assets/i18n/vi_VN.json @@ -55,6 +55,8 @@ "account.storage_unavailable": "Không có bộ nhớ", "account.the_server_did_not_sign_out": "Máy chủ không đăng xuất.", "account.use_https_or_http_on_localhost_for_development": "Sử dụng HTTPS hoặc HTTP trên localhost để phát triển.", + "app.show_or_hide_the_printer_or_tool_volume": "Hiện hoặc ẩn khối tham chiếu", + "app.the_model_is_outside_the_printer_or_tool_volume": "Mô hình vượt ra ngoài khối tham chiếu.", "agent_link.activity.batch": "Đang áp dụng một loạt thay đổi", "agent_link.activity.checking": "Đang kiểm tra mô hình", "agent_link.activity.creating": "Đang tạo hình học", @@ -1345,6 +1347,7 @@ "realtime.websocket_disconnected_2": "WebSocket đã bị ngắt kết nối: {e}", "realtime.websocket_host_missing": "WebSocket", "realtime.websocket_unavailable": "WebSocket không có sẵn", + "reference_volume.show": "Hiện khối tham chiếu", "release_notes.format": "•", "release_notes.latest": " · Mới nhất", "release_notes.newer": "Mới hơn", @@ -1467,6 +1470,12 @@ "router.suspended": "Định tuyến trên cạnh #{id} bị tạm dừng: {error}", "router.width": "Chiều rộng", "section_gizmo.drag_section_along_its_axis_esc_to_cancel": "Kéo mặt cắt {} dọc theo trục · Esc để hủy. Khi nhìn dọc theo trục, hãy kéo lên/xuống.", + "settings.printer_and_tool_volume": "Khối tham chiếu", + "settings.a_locked_reference_box_for_a_printer_s_build": "Một khung tham chiếu cố định để kiểm tra xem đối tượng có vừa trong không gian đã chọn hay không.", + "settings.width_x": "Chiều rộng (X)", + "settings.depth_y": "Chiều sâu (Y)", + "settings.height_z": "Chiều cao (Z)", + "settings.clear_the_toggle_shortcut": "Xóa phím tắt của khối tham chiếu.", "settings.adjust_mouse_and_trackpad_navigation_sensitivity": "Điều chỉnh độ nhạy điều hướng bằng chuột và bàn di chuột.", "settings.automatically_group_new_shapes": "Tự động nhóm các hình mới", "settings.automatically_size_grid_when_zooming": "Tự điều chỉnh kích thước lưới khi thu phóng", @@ -1514,6 +1523,7 @@ "settings.snap_to_grid": "Bắt theo lưới", "settings.spacing_controls_both_grid_lines_and_grid_snapping": "Khoảng cách điều khiển cả đường lưới và thao tác bắt lưới. Mỗi đường thứ năm được làm nổi bật.", "settings.system": "Hệ thống", + "settings.toggle_reference_volume": "Bật/tắt khối tham chiếu", "settings.tool": "Công cụ", "settings.tools": "Công cụ", "settings.tools_for_checking_performance_and_troubleshooting": "Công cụ kiểm tra hiệu năng và khắc phục sự cố.", diff --git a/assets/i18n/zh_CN.json b/assets/i18n/zh_CN.json index 3a5e228..36e4079 100644 --- a/assets/i18n/zh_CN.json +++ b/assets/i18n/zh_CN.json @@ -55,6 +55,8 @@ "account.storage_unavailable": "存储不可用", "account.the_server_did_not_sign_out": "服务器未执行退出登录。", "account.use_https_or_http_on_localhost_for_development": "开发时请使用 HTTPS,或在 localhost 上使用 HTTP。", + "app.show_or_hide_the_printer_or_tool_volume": "显示或隐藏参考空间", + "app.the_model_is_outside_the_printer_or_tool_volume": "模型超出了参考空间。", "agent_link.activity.batch": "正在批量应用更改", "agent_link.activity.checking": "正在检查模型", "agent_link.activity.creating": "正在创建几何体", @@ -1350,6 +1352,7 @@ "realtime.websocket_disconnected_2": "WebSocket 已断开:{e}", "realtime.websocket_host_missing": "缺少 WebSocket 主机", "realtime.websocket_unavailable": "WebSocket 不可用", + "reference_volume.show": "显示参考空间", "release_notes.format": "•", "release_notes.latest": " · 最新", "release_notes.newer": "较新", @@ -1472,6 +1475,12 @@ "router.suspended": "在边 #{id} 上的铣削操作已暂停:{error}", "router.width": "宽度", "section_gizmo.drag_section_along_its_axis_esc_to_cancel": "沿其轴拖动剖切面 {} · 按 Esc 取消。沿轴方向观察时,请上下拖动。", + "settings.printer_and_tool_volume": "参考空间", + "settings.a_locked_reference_box_for_a_printer_s_build": "用于检查对象是否适合指定空间的固定参考框。", + "settings.width_x": "宽度 (X)", + "settings.depth_y": "深度 (Y)", + "settings.height_z": "高度 (Z)", + "settings.clear_the_toggle_shortcut": "清除参考空间快捷键。", "settings.adjust_mouse_and_trackpad_navigation_sensitivity": "调整鼠标和触控板的导航灵敏度。", "settings.automatically_group_new_shapes": "自动为新形状分组", "settings.automatically_size_grid_when_zooming": "缩放时自动调整网格尺寸", @@ -1519,6 +1528,7 @@ "settings.snap_to_grid": "捕捉到网格", "settings.spacing_controls_both_grid_lines_and_grid_snapping": "间距同时控制网格线和网格捕捉。每第五条线会加粗显示。", "settings.system": "系统", + "settings.toggle_reference_volume": "切换参考空间", "settings.tool": "工具", "settings.tools": "工具", "settings.tools_for_checking_performance_and_troubleshooting": "用于检查性能和排查问题的工具。", diff --git a/crates/benchup-app/src/agent_effects.rs b/crates/benchup-app/src/agent_effects.rs index 0d224a2..d69a581 100644 --- a/crates/benchup-app/src/agent_effects.rs +++ b/crates/benchup-app/src/agent_effects.rs @@ -611,13 +611,14 @@ impl Drop for Draw { } struct TargetSrgb(bool); -// Precision renderer packets share their retained geometry across animation -// frames. Each pane owns its uniform, so split views cannot overwrite cameras. +// Precision renderer packets share retained geometry across animation and +// volume-bound changes. Each pane owns its uniform and projection. #[repr(C)] #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] struct ProjectedUniform { parameters: [f32; 4], size: [f32; 4], + volume: reference_volume::Parameters, } pub(super) struct Projected { uniform: ProjectedUniform, @@ -632,6 +633,7 @@ struct ProjectedPipelines { edges: wgpu::RenderPipeline, empty: wgpu::TextureView, sampler: wgpu::Sampler, + srgb: bool, } pub(super) fn projected_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { @@ -712,11 +714,13 @@ pub(super) fn install_projected( edges: pipeline(PipelinePass::Edges), empty, sampler: device.create_sampler(&Default::default()), + srgb: format.is_srgb(), }); } impl Projected { - pub(super) fn new(frame: &Frame, camera: &Camera, rect: Rect) -> Option { - frame.animated().then(|| Self { + pub(super) fn new(frame: &Frame, camera: &Camera, rect: Rect, + volume: Option<(DVec3, DVec3)>, projection: (glam::DMat4, [f32; 4])) -> Option { + (frame.animated() || volume.is_some()).then(|| Self { uniform: ProjectedUniform { parameters: frame.parameters(camera, rect), size: [ @@ -725,6 +729,7 @@ impl Projected { if frame.starts.is_empty() { 0. } else { 1. }, 0., ], + volume: reference_volume::Parameters::new(volume, projection), }, gpu: OnceLock::new(), }) @@ -737,9 +742,11 @@ impl Projected { ) { if let Some(pipelines) = resources.get::() { self.gpu.get_or_init(|| { + let mut uniform = self.uniform; + uniform.size[3] = if pipelines.srgb { 1. } else { 0. }; let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("Agent precision scene animation"), - contents: bytemuck::bytes_of(&self.uniform), + label: Some("Precision scene effects"), + contents: bytemuck::bytes_of(&uniform), usage: wgpu::BufferUsages::UNIFORM, }); let view = scene diff --git a/crates/benchup-app/src/app.rs b/crates/benchup-app/src/app.rs index d948fb6..6116703 100644 --- a/crates/benchup-app/src/app.rs +++ b/crates/benchup-app/src/app.rs @@ -69,6 +69,8 @@ pub(crate) mod surface_appearance; mod grid; #[path = "grain_direction.rs"] mod grain_direction; +#[path = "printer_volume.rs"] +mod printer_volume; #[path = "measurement_tools.rs"] mod measurement_tools; #[path = "move_tool.rs"] @@ -2734,6 +2736,12 @@ impl BenchUpApp { self.set_tool(tool); continue; } + // Tool shortcuts win over the volume toggle, so a conflicting + // assignment can never shadow a tool. + if self.general_settings.volume.hotkey() == Some(key) { + self.toggle_printer_volume(ctx); + continue; + } match key { Key::Delete => self.erase_selected(ctx), Key::Backspace => { @@ -5947,6 +5955,8 @@ impl BenchUpApp { && self.measurement.as_ref().is_none_or(|m| { m.complete && m.dimension_id.is_some() && self.length_input.trim().is_empty() }); + let reference_bounds = self.general_settings.volume.visible + .then(|| self.general_settings.volume.bounds()); let key = ((self.modeling.is_none() || self.tool == Tool::Scale) && self.grain_anchor.is_none() && self.paste_preview.is_none() @@ -5964,6 +5974,7 @@ impl BenchUpApp { display: display.clone(), surface_catalog: surface_catalog.clone(), dark: ui.visuals().dark_mode, + reference_bounds, tool: self.tool, selected: selected.clone(), hover, @@ -6003,6 +6014,9 @@ impl BenchUpApp { references.axis_line(camera, -v, DVec3::ZERO, 0.85, self.axis_color(axis).gamma_multiply(0.35)); references.axis_line(camera, DVec3::ZERO, v, 1.1, self.axis_color(axis).gamma_multiply(0.8)); } + if self.general_settings.volume.visible { + self.general_settings.volume.paint(&mut references); + } self.add_drawing_preview(&mut references, camera, ui); self.scene_cache.paint_resident(key, model, &self.face_cache, entities, ui, rect, references); self.picking_cache.update(&self.face_cache); @@ -6053,7 +6067,10 @@ impl BenchUpApp { && !selected_entities.is_empty(); let mut mesh = renderer::Mesh::cached(camera, size, &mut self.scene_cache); mesh.remap_agent_effects(model); - mesh.set_scene_clip_planes(camera, self.render_model.bounds()); + mesh.set_scene_clip_planes(camera, renderer::include_reference_bounds( + self.render_model.bounds(), reference_bounds, + )); + mesh.set_reference_bounds(reference_bounds); mesh.reference_image_depth_bounds(model); mesh.set_pixels_per_point(ui.ctx().pixels_per_point()); mesh.set_display(display); @@ -6275,6 +6292,9 @@ impl BenchUpApp { display, &faces, ); + if self.general_settings.volume.visible { + self.general_settings.volume.paint(&mut mesh); + } let grain_preview = self.history_preview.is_none() .then(|| self.grain_preview_axes()) .unwrap_or_default(); @@ -6976,6 +6996,7 @@ impl BenchUpApp { p.galley(r.min + egui::vec2(12., 10.), galley, colors.ink); } } + self.paint_volume_warning(ui.ctx(), &p, rect, colors.paper, colors.ink, cache_revision); } fn edit_context_bar(&mut self, ui: &mut egui::Ui) { let colors = Palette::for_ui(ui); diff --git a/crates/benchup-app/src/app_tests.rs b/crates/benchup-app/src/app_tests.rs index c756c1c..9d17251 100644 --- a/crates/benchup-app/src/app_tests.rs +++ b/crates/benchup-app/src/app_tests.rs @@ -7681,3 +7681,248 @@ fn focus_picker_highlights_like_pointer_without_selecting() { #[path = "follow_me_ui_tests.rs"] mod follow_me_ui_tests; + +#[test] +fn toggling_the_printer_volume_frames_it_and_leaves_the_camera_alone_when_hidden() { + let mut h = Harness::new(); + h.app.general_settings.volume = printer_volume::Settings { + visible: false, + size_m: [0.256, 0.256, 0.256], + ..Default::default() + }; + let before = h.app.doc.camera.clone(); + + h.app.toggle_printer_volume(&h.ctx); + assert!(h.app.general_settings.volume.visible); + + // The framed target is the volume's centre: X/Y on the origin, half the + // height up, because the base sits on Z = 0. + let target = h.app.doc.camera.target; + assert!(target.x.abs() < 1e-9, "x {}", target.x); + assert!(target.y.abs() < 1e-9, "y {}", target.y); + assert!((target.z - 0.128).abs() < 1e-9, "z {}", target.z); + assert!( + h.app.doc.camera.distance < before.distance, + "fitting should move the camera closer: {} -> {}", + before.distance, + h.app.doc.camera.distance + ); + + // Hiding the box must not disturb the view. + let framed = h.app.doc.camera.clone(); + h.app.toggle_printer_volume(&h.ctx); + assert!(!h.app.general_settings.volume.visible); + assert_eq!(h.app.doc.camera.target, framed.target); + assert_eq!(h.app.doc.camera.distance, framed.distance); +} + +#[test] +fn reference_volume_is_below_sections_and_toggles_from_the_view_menu() { + let mut h = Harness::new(); + let output = h.frame(vec![], egui::Modifiers::NONE); + h.click(text_position(&output, tr!("app.view"))); + let output = h.frame(vec![], egui::Modifiers::NONE); + let sections = text_position(&output, tr!("view_controls.sections")); + let reference = text_position(&output, tr!("settings.printer_and_tool_volume")); + assert!(reference.y > sections.y); + h.click(reference); + let output = h.frame(vec![], egui::Modifiers::NONE); + for label in [tr!("settings.width_x"), tr!("settings.depth_y"), tr!("settings.height_z")] { + text_position(&output, label); + } + h.click(text_position(&output, tr!("reference_volume.show"))); + assert!(h.app.general_settings.volume.visible); + let output = h.frame(vec![], egui::Modifiers::NONE); + h.click(text_position(&output, tr!("reference_volume.show"))); + assert!(!h.app.general_settings.volume.visible); +} + +#[test] +fn volume_warning_is_gated_on_visibility_and_geometry() { + let mut h = Harness::new(); + h.app.general_settings.volume = printer_volume::Settings { + visible: true, + size_m: [0.256, 0.256, 0.256], + ..Default::default() + }; + assert!(!h.app.volume_exceeded(&h.ctx, 1), "an empty model fits the volume"); + + // A board well past the 256 mm cube. + h.app + .doc + .model + .add_edge(DVec3::new(-2., -2., 0.), DVec3::new(2., 2., 2.)) + .unwrap(); + // A new scene revision is what invalidates the memoized answer. + assert!( + h.app.volume_exceeded(&h.ctx, 2), + "geometry outside the volume must raise the warning" + ); + // Same revision reuses the cached answer. + assert!(h.app.volume_exceeded(&h.ctx, 2)); + + h.app.general_settings.volume.visible = false; + assert!( + !h.app.volume_exceeded(&h.ctx, 3), + "hiding the box must also hide the warning" + ); +} + +#[test] +fn shortcut_toggles_the_printer_volume_through_the_keyboard() { + let mut h = Harness::new(); + h.app.general_settings.volume = printer_volume::Settings { + visible: false, + hotkey: Some("V".into()), + ..Default::default() + }; + let event = |pressed| egui::Event::Key { + key: Key::V, + physical_key: None, + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + let press = |h: &mut Harness| { + h.frame(vec![event(true)], egui::Modifiers::NONE); + h.frame(vec![event(false)], egui::Modifiers::NONE); + }; + + press(&mut h); + assert!(h.app.general_settings.volume.visible, "V shows the volume"); + press(&mut h); + assert!(!h.app.general_settings.volume.visible, "V hides it again"); +} + +/// The volume is a viewport reference, never document content. These tests pin the +/// boundary so saving, exporting, selecting and copying can never pick it up. +#[test] +fn volume_settings_never_enter_the_saved_document() { + let mut h = Harness::new(); + h.app + .doc + .model + .add_edge(DVec3::ZERO, DVec3::X * 2.) + .unwrap(); + let before = serde_json::to_string(&h.app.doc).unwrap(); + + h.app.general_settings.volume.visible = true; + h.app.general_settings.volume.size_m = [7., 7., 7.]; + h.app.general_settings.volume.hotkey = Some("V".into()); + + let after = serde_json::to_string(&h.app.doc).unwrap(); + assert_eq!( + before, after, + "volume settings must not reach the document that is saved" + ); + for key in ["size_m", "hotkey"] { + assert!( + !after.contains(key), + "saved document must not contain {key}" + ); + } +} + +#[test] +fn the_volume_is_never_selectable() { + fn select_all(h: &mut Harness) { + // egui needs the matching release, like Harness::key does. + let modifiers = egui::Modifiers::CTRL; + for pressed in [true, false] { + h.frame( + vec![egui::Event::Key { + key: Key::A, + physical_key: None, + pressed, + repeat: false, + modifiers, + }], + modifiers, + ); + } + } + + let mut h = Harness::new(); + h.app.general_settings.volume = printer_volume::Settings { + visible: true, + ..Default::default() + }; + // Only the volume is on screen; select all must still find nothing. + select_all(&mut h); + assert!( + h.app.selected.is_empty(), + "the volume must not be selectable: {:?}", + h.app.selected + ); + + // With real geometry, select all still selects only model entities. + h.app + .doc + .model + .add_edge(DVec3::ZERO, DVec3::X * 2.) + .unwrap(); + select_all(&mut h); + assert_eq!(h.app.selected, h.app.doc.model.selectable_entities()); + assert!( + h.app + .selected + .iter() + .all(|id| h.app.doc.model.contains_entity(id)), + "every selected id must be a model entity" + ); +} + +#[test] +fn copying_with_only_the_volume_visible_captures_nothing() { + let mut h = Harness::new(); + h.app.general_settings.volume = printer_volume::Settings { + visible: true, + ..Default::default() + }; + h.frame(vec![egui::Event::Copy], egui::Modifiers::NONE); + assert!( + h.app.clipboard.is_none(), + "copy must ignore the volume and stay empty with no selection" + ); + + let id = h + .app + .doc + .model + .add_edge(DVec3::ZERO, DVec3::X * 2.) + .unwrap(); + h.app.selected.insert(id); + h.frame(vec![egui::Event::Copy], egui::Modifiers::NONE); + let clipboard = h.app.clipboard.as_ref().expect("the selected edge is copied"); + assert_eq!(clipboard.model.edges.len(), 1); + assert_eq!( + clipboard.model.vertices.len(), + 2, + "only the selected edge's vertices travel, no volume geometry" + ); +} + +#[test] +fn exports_contain_only_model_geometry() { + let mut h = Harness::new(); + h.app + .doc + .model + .add_edge(DVec3::ZERO, DVec3::X * 2.) + .unwrap(); + let hidden = crate::interchange::export_obj(&h.app.doc.model).unwrap(); + + h.app.general_settings.volume = printer_volume::Settings { + visible: true, + size_m: [3., 3., 3.], + ..Default::default() + }; + let shown = crate::interchange::export_obj(&h.app.doc.model).unwrap(); + + assert_eq!( + hidden, shown, + "showing the volume must not change exported geometry" + ); + let vertices = shown.lines().filter(|line| line.starts_with("v ")).count(); + assert_eq!(vertices, 2, "only the model's own two vertices are exported"); +} diff --git a/crates/benchup-app/src/edges.wgsl b/crates/benchup-app/src/edges.wgsl index 8f9df8b..8b7a851 100644 --- a/crates/benchup-app/src/edges.wgsl +++ b/crates/benchup-app/src/edges.wgsl @@ -237,10 +237,14 @@ fn grain_direction_coverage(packed: vec4, dx: vec4, dy: vec4, wid return coverage; } -// Precision display modes retain their projected buffers too. Only these -// fragment variants consume the live animation parameters; ordinary rendering -// and offscreen shadow masks keep their existing binding layouts. -struct AgentEffect { parameters: vec4, size: vec4 } +// Precision display modes retain their projected buffers too. Face fragments +// combine live animation and reference-volume bounds without new geometry; +// ordinary rendering and offscreen masks keep their existing binding layouts. +struct AgentEffect { + parameters: vec4, size: vec4, + volume_inverse: mat4x4, volume_depth: vec4, + volume_low: vec4, volume_high: vec4, +} @group(0) @binding(2) var agent_effect: AgentEffect; fn active_stamp(stamp: f32) -> f32 { // Old retained vertices must not reassemble when the timer wraps later. @@ -249,6 +253,22 @@ fn active_stamp(stamp: f32) -> f32 { fn animated_color(input: EdgeVertex, color: vec4) -> vec4 { return agent_surface(color, active_stamp(input.effect), input.uv, agent_effect.size.xy, agent_effect.parameters); } +fn projected_face_color(input: EdgeVertex, color: vec4) -> vec4 { + let animated = animated_color(input, color); + if agent_effect.volume_low.w == 0.0 { return animated; } + var depth = input.position.z; + if agent_effect.volume_depth.w != 0.0 { + depth = agent_effect.volume_depth.x + (depth - agent_effect.volume_depth.z) * agent_effect.volume_depth.y / 0.8; + } + let world = agent_effect.volume_inverse * vec4(input.uv * vec2(2.0, -2.0) + vec2(-1.0, 1.0), depth, 1.0); + return reference_overflow_tint(animated, world.xyz / world.w, + agent_effect.volume_low, agent_effect.volume_high, agent_effect.size.w != 0.0); +} +@fragment fn fragment_faces_effect(input: EdgeVertex) -> @location(0) vec4 { + let coverage = stroke_coverage(input); + if coverage < 0.001 { discard; } + return projected_face_color(input, input.color) * coverage; +} @fragment fn fragment_main_effect(input: EdgeVertex) -> @location(0) vec4 { let coverage = stroke_coverage(input); if coverage < 0.001 { discard; } @@ -264,16 +284,16 @@ fn animated_color(input: EdgeVertex, color: vec4) -> vec4 { let coverage = stroke_coverage(input); let color = shade_finish(input, input.color, 0.0); if coverage < 0.001 { discard; } - return animated_color(input, color) * coverage; + return projected_face_color(input, color) * coverage; } @fragment fn fragment_shadow_faces_effect(input: EdgeVertex) -> @location(0) vec4 { let coverage = textureSample(shadow_mask, shadow_sampler, input.uv).r; let color = mix(input.color, input.shadow_color, coverage * select(0.0, 1.0, input.shadow_color.a > 0.0)); - return animated_color(input, color); + return projected_face_color(input, color); } @fragment fn fragment_material_shadow_faces_effect(input: EdgeVertex) -> @location(0) vec4 { let coverage = textureSample(shadow_mask, shadow_sampler, input.uv).r; let amount = coverage * select(0.0, 1.0, input.shadow_color.a > 0.0); let color = shade_finish(input, mix(input.color, input.shadow_color, amount), amount); - return animated_color(input, color); + return projected_face_color(input, color); } diff --git a/crates/benchup-app/src/icons.rs b/crates/benchup-app/src/icons.rs index 90d949b..797d777 100644 --- a/crates/benchup-app/src/icons.rs +++ b/crates/benchup-app/src/icons.rs @@ -1605,6 +1605,36 @@ fn paint_line_icon(p: &egui::Painter, c: Pos2, kind: &str, color: Color32) { s, )); } + "warning" => { + p.add(egui::Shape::convex_polygon( + vec![at(0., -9.), at(9., 7.), at(-9., 7.)], + color, + Stroke::NONE, + )); + let ink = Color32::from_rgb(65, 36, 0); + p.line_segment([at(0., -3.5), at(0., 1.)], Stroke::new(1.8, ink)); + p.circle_filled(at(0., 4.), 1., ink); + } + "reference_volume" => { + // Isometric box for the fixed reference volume. + let front = [ + at(-8., 2.), + at(-2., 2.), + at(-2., 8.), + at(-8., 8.), + ]; + let back = [ + at(-3., -3.), + at(3., -3.), + at(3., 3.), + at(-3., 3.), + ]; + p.add(egui::Shape::closed_line(front.to_vec(), s)); + p.add(egui::Shape::closed_line(back.to_vec(), s)); + for corner in 0..4 { + p.line_segment([front[corner], back[corner]], s); + } + } _ => {} } } diff --git a/crates/benchup-app/src/printer_volume.rs b/crates/benchup-app/src/printer_volume.rs new file mode 100644 index 0000000..784477f --- /dev/null +++ b/crates/benchup-app/src/printer_volume.rs @@ -0,0 +1,435 @@ +use super::*; + +/// A user-defined reference volume drawn as a locked wireframe in the viewport. +/// +/// The volume is a global preference, not document geometry, so the same space +/// can be checked across projects. It cannot be selected, edited, or moved. +/// Limits in metres, from small parts up to room-sized reference spaces. +pub(super) const MIN_M: f64 = 0.001; +pub(super) const MAX_M: f64 = 100.; + +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub(super) struct Settings { + /// Draw the wireframe box in the viewport. + pub visible: bool, + /// Width (X), depth (Y) and height (Z) in metres, matching the model space. + /// The settings UI converts to and from the user's display units, so a user + /// working in feet sees and enters feet while the stored value stays exact. + pub size_m: [f64; 3], + /// Optional shortcut that toggles `visible`. Unassigned by default. + pub hotkey: Option, +} + +impl Default for Settings { + fn default() -> Self { + Self { + visible: false, + // A compact starting reference; users set the space they need. + size_m: [0.256, 0.256, 0.256], + hotkey: None, + } + } +} + +impl Settings { + /// Keep saved preferences usable. Older files lack these fields entirely and + /// `#[serde(default)]` supplies them; damaged values fall back per axis so one + /// bad dimension never discards the others. + pub(super) fn sanitize(&mut self) { + let fallback = Self::default().size_m; + for (value, default) in self.size_m.iter_mut().zip(fallback) { + if !value.is_finite() { + *value = default; + } + *value = value.clamp(MIN_M, MAX_M); + } + if let Some(key) = &self.hotkey + && !super::shortcut_input::valid_tool_key(key) + { + self.hotkey = None; + } + } + + pub(super) fn toggle(&mut self) { + self.visible = !self.visible; + } + + /// A stored axis length expressed in `unit`. The value is always held in + /// metres, so switching display units re-presents the same physical volume. + pub(super) fn axis_in(&self, axis: usize, unit: benchup_core::LengthUnit) -> f64 { + self.size_m[axis] / unit.factor() + } + + /// Store an axis length entered in `unit`. + pub(super) fn set_axis_from( + &mut self, + axis: usize, + value: f64, + unit: benchup_core::LengthUnit, + ) { + self.size_m[axis] = value * unit.factor(); + } + + /// Half extent of the volume in metres. + fn half_extent(&self) -> DVec3 { + DVec3::new(self.size_m[0], self.size_m[1], self.size_m[2]) * 0.5 + } + + /// The occupied region in model space: centred on the origin in X and Y, and + /// sitting on Z = 0. That puts the bottom face's centre at the origin. + pub(super) fn bounds(&self) -> (DVec3, DVec3) { + let half = self.half_extent(); + ( + DVec3::new(-half.x, -half.y, 0.), + DVec3::new(half.x, half.y, self.size_m[2]), + ) + } + + /// True when the given bounds fit inside the volume. Touching counts as + /// fitting, so geometry exactly on the boundary is not flagged. + pub(super) fn contains(&self, low: DVec3, high: DVec3) -> bool { + let (min, max) = self.bounds(); + let tolerance = 1e-9; + (0..3).all(|axis| { + low[axis] >= min[axis] - tolerance && high[axis] <= max[axis] + tolerance + }) + } + + /// Any geometry outside the volume means a vertex is outside, and therefore + /// that the model's bounds leave the volume, so one bounds test is exact and + /// far cheaper than walking every vertex. + pub(super) fn exceeds(&self, model: &Model) -> bool { + model + .bounds() + .is_some_and(|(low, high)| !self.contains(low, high)) + } + + pub(super) fn hotkey(&self) -> Option { + self.hotkey + .as_deref() + .and_then(egui::Key::from_name) + } + + /// The shared reference-mesh API consumes projected strips, so preparation + /// is bounded to twelve segments and reused on unchanged frames. Keeping + /// these tiny references separate leaves the model's GPU buffers resident. + pub(super) fn paint(&self, mesh: &mut renderer::Mesh) { + let (min, max) = self.bounds(); + let corners = [ + DVec3::new(min.x, min.y, min.z), + DVec3::new(max.x, min.y, min.z), + DVec3::new(max.x, max.y, min.z), + DVec3::new(min.x, max.y, min.z), + DVec3::new(min.x, min.y, max.z), + DVec3::new(max.x, min.y, max.z), + DVec3::new(max.x, max.y, max.z), + DVec3::new(min.x, max.y, max.z), + ]; + const EDGES: [(usize, usize); 12] = [ + (0, 1), + (1, 2), + (2, 3), + (3, 0), + (4, 5), + (5, 6), + (6, 7), + (7, 4), + (0, 4), + (1, 5), + (2, 6), + (3, 7), + ]; + for (a, b) in EDGES { + mesh.reference_line(corners[a], corners[b], 1.5, ACCENT, true); + } + } +} + +impl BenchUpApp { + pub(super) fn reference_volume_menu(&mut self, ui: &mut egui::Ui) { + let button = egui::Button::new((Self::menu_item_icon(ui, Some("reference_volume")), tr!("settings.printer_and_tool_volume"))) + .gap(ui.spacing().icon_spacing) + .right_text(egui::menu::SubMenuButton::arrow_atom(None)); + egui::menu::SubMenuButton::from_button(button) + .config(egui::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)) + .ui(ui, |ui| { + Self::menu_style(ui.style_mut()); + ui.set_width(264.); + self.reference_volume_controls(ui); + }); + } + + pub(super) fn reference_volume_controls(&mut self, ui: &mut egui::Ui) { + let mut visible = self.general_settings.volume.visible; + if Self::menu_checkbox(ui, &mut visible, tr!("reference_volume.show")) + .on_hover_text(tr!("app.show_or_hide_the_printer_or_tool_volume")).changed() + { + self.toggle_printer_volume(ui.ctx()); + } + ui.text_weak(tr!("settings.a_locked_reference_box_for_a_printer_s_build")); + ui.separator(); + let units = self.doc.display.units; + let length = units.length; + let factor = length.factor(); + let decimals = units.precision.length.unwrap_or(3) as usize; + let mut table = crate::inspector_table::InspectorTable::new( + ui.available_width(), + [crate::inspector_table::Column::flex(0.5), crate::inspector_table::Column::flex(0.5)], + ); + for (axis, label) in [tr!("settings.width_x"), tr!("settings.depth_y"), tr!("settings.height_z")].into_iter().enumerate() { + table.row(ui, ("settings_volume_axis", axis), |column, ui| { + if column == 0 { + ui.text_label(label); + } else { + let mut value = self.general_settings.volume.axis_in(axis, length); + if ui.add(egui::DragValue::new(&mut value).speed(1.).max_decimals(decimals) + .range(MIN_M / factor..=MAX_M / factor).suffix(format!(" {}", length.symbol()))).changed() + { + self.general_settings.volume.set_axis_from(axis, value, length); + } + } + }); + } + } + + pub(super) fn reference_volume_shortcut(&mut self, ui: &mut egui::Ui) { + ui.horizontal(|ui| { + let assigned = self.general_settings.volume.hotkey.is_some(); + let shown = self.general_settings.volume.hotkey.clone().unwrap_or_else(|| tr!("common.none").into()); + let width = (ui.available_width() - if assigned { 32. } else { 0. }).max(24.); + if let Some(key) = super::shortcut_input::shortcut_input(ui, "settings_volume_key", &shown, width) { + self.general_settings.volume.hotkey = Some(key); + } + if assigned { + let clear = ui.small_button("✕").on_hover_text(tr!("settings.clear_the_toggle_shortcut")); + clear.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr!("settings.clear_the_toggle_shortcut"))); + if clear.clicked() { self.general_settings.volume.hotkey = None; } + } + }); + } + + /// Toggling on frames the reference, which can be tiny at the current zoom. + /// Toggling off leaves the camera untouched. + pub(super) fn toggle_printer_volume(&mut self, ctx: &egui::Context) { + self.general_settings.volume.toggle(); + if self.general_settings.volume.visible { + self.doc.camera.fit( + Some(self.general_settings.volume.bounds()), + dv(self.viewport.size().max(Vec2::splat(1.))), + ); + self.changed(ctx); + } + ctx.request_repaint(); + } + + /// `Model::bounds` expands visibility and walks geometry, so it must not run + /// every frame. Cache the answer against the caller's scene revision, which + /// advances on every model change, plus the volume's own dimensions. + pub(super) fn volume_exceeded(&self, ctx: &egui::Context, revision: u64) -> bool { + if !self.general_settings.volume.visible { + return false; + } + let id = egui::Id::unique("printer_volume_warning"); + let size = self.general_settings.volume.size_m; + if let Some((cached_revision, cached_size, exceeded)) = + ctx.data(|data| data.get_temp::<(u64, [f64; 3], bool)>(id)) + && cached_revision == revision + && cached_size == size + { + return exceeded; + } + let exceeded = self.general_settings.volume.exceeds(&self.doc.model); + ctx.data_mut(|data| data.insert_temp(id, (revision, size, exceeded))); + exceeded + } + + /// Persistent viewport banner while any geometry leaves the volume. It is + /// gated on the box being visible, so hiding the ghost also hides the warning. + pub(super) fn paint_volume_warning( + &self, + ctx: &egui::Context, + painter: &egui::Painter, + rect: Rect, + paper: Color32, + ink: Color32, + revision: u64, + ) { + if !self.volume_exceeded(ctx, revision) { + return; + } + let galley = painter.layout( + tr!("app.the_model_is_outside_the_printer_or_tool_volume").to_owned(), + FontId::proportional(12.), + ink, + (rect.width() - 106.).clamp(160., 494.), + ); + let banner = Rect::from_center_size( + Pos2::new(rect.center().x, rect.top() + 30.), + egui::vec2(galley.size().x + 50., galley.size().y.max(18.) + 16.), + ); + painter.rect_filled(banner, 7, paper); + painter.rect_stroke( + banner, + 7, + Stroke::new(1., ink.gamma_multiply(0.5)), + egui::StrokeKind::Inside, + ); + icons::line_icon( + painter, + Pos2::new(banner.left() + 21., banner.center().y), + "warning", + Color32::from_rgb(245, 155, 45), + ); + let text_top = banner.center().y - galley.size().y * 0.5; + painter.galley(Pos2::new(banner.left() + 38., text_top), galley, ink); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_are_hidden_with_an_unassigned_shortcut() { + let settings = Settings::default(); + assert!(!settings.visible); + assert_eq!(settings.hotkey, None); + assert_eq!(settings.size_m, [0.256, 0.256, 0.256]); + } + + #[test] + fn bottom_face_center_sits_on_the_origin() { + let settings = Settings { + size_m: [0.2, 0.1, 0.05], + ..Default::default() + }; + let (min, max) = settings.bounds(); + assert_eq!(min.x, -0.1); + assert_eq!(max.x, 0.1); + assert_eq!(min.y, -0.05); + assert_eq!(max.y, 0.05); + // The base rests on the ground plane and the height extends upward. + assert_eq!(min.z, 0.); + assert!((max.z - 0.05).abs() < 1e-12); + assert!((min.x + max.x).abs() < 1e-12, "X is centred on the origin"); + assert!((min.y + max.y).abs() < 1e-12, "Y is centred on the origin"); + } + + #[test] + fn touching_the_volume_still_fits() { + let settings = Settings { + size_m: [0.1, 0.1, 0.1], + ..Default::default() + }; + let (min, max) = settings.bounds(); + assert!(settings.contains(min, max)); + assert!(settings.contains(min, max + DVec3::splat(1e-12))); + } + + #[test] + fn geometry_outside_the_volume_is_detected() { + let settings = Settings { + size_m: [0.1, 0.1, 0.1], + ..Default::default() + }; + let (min, max) = settings.bounds(); + // Above the height. + assert!(!settings.contains(min, max + DVec3::Z * 0.001)); + // Below the bed. + assert!(!settings.contains(min - DVec3::Z * 0.001, max)); + // Beyond a side. + assert!(!settings.contains(min, max + DVec3::X * 0.001)); + assert!(!settings.contains(min - DVec3::Y * 0.001, max)); + } + + #[test] + fn damaged_sizes_fall_back_per_axis_and_extremes_clamp() { + // One damaged axis keeps the user's other two values. + let mut settings = Settings { + size_m: [f64::NAN, 0.01, 0.01], + ..Default::default() + }; + settings.sanitize(); + assert_eq!(settings.size_m, [Settings::default().size_m[0], 0.01, 0.01]); + + let mut settings = Settings { + size_m: [-5., 1e9, 0.05], + hotkey: Some("nope".into()), + ..Default::default() + }; + settings.sanitize(); + assert_eq!(settings.size_m, [MIN_M, MAX_M, 0.05]); + assert_eq!(settings.hotkey, None, "an invalid key is dropped"); + } + + #[test] + fn valid_hotkey_survives_sanitize() { + let mut settings = Settings { + hotkey: Some("V".into()), + ..Default::default() + }; + settings.sanitize(); + assert_eq!(settings.hotkey.as_deref(), Some("V")); + assert_eq!(settings.hotkey(), Some(egui::Key::V)); + } + + #[test] + fn switching_display_units_re_presents_the_same_physical_volume() { + use benchup_core::LengthUnit; + let settings = Settings::default(); + + // The default 256 mm cube reads as millimetres, centimetres and feet. + assert!((settings.axis_in(0, LengthUnit::Millimeters) - 256.).abs() < 1e-9); + assert!((settings.axis_in(0, LengthUnit::Centimeters) - 25.6).abs() < 1e-9); + assert!((settings.axis_in(2, LengthUnit::Millimeters) - 256.).abs() < 1e-9); + let feet = settings.axis_in(0, LengthUnit::Feet); + assert!((feet - 0.256 / 0.3048).abs() < 1e-12, "got {feet} ft"); + + // What the user types in one unit lands as the same physical size. + let mut settings = Settings::default(); + settings.set_axis_from(0, 1., LengthUnit::Feet); + assert!((settings.size_m[0] - 0.3048).abs() < 1e-12); + assert!((settings.axis_in(0, LengthUnit::Millimeters) - 304.8).abs() < 1e-9); + + // Switching units must not change the stored value. + let before = settings.size_m; + let _ = settings.axis_in(0, LengthUnit::Inches); + assert_eq!(settings.size_m, before); + } + + #[test] + fn toggle_flips_visibility_only() { + let mut settings = Settings::default(); + settings.toggle(); + assert!(settings.visible); + settings.toggle(); + assert!(!settings.visible); + } + #[test] + fn bounds_follow_the_configured_size() { + for size in [[0.1, 0.2, 0.3], [1., 1., 1.], [0.256, 0.256, 0.256]] { + let settings = Settings { + size_m: size, + ..Default::default() + }; + let (min, max) = settings.bounds(); + assert!((min.x + size[0] / 2.).abs() < 1e-12); + assert!((max.x - size[0] / 2.).abs() < 1e-12); + assert!((min.y + size[1] / 2.).abs() < 1e-12); + assert!((max.y - size[1] / 2.).abs() < 1e-12); + assert_eq!(min.z, 0.); + assert!((max.z - size[2]).abs() < 1e-12); + } + } + + #[test] + fn an_empty_model_never_exceeds_the_volume() { + let settings = Settings { + size_m: [0.001, 0.001, 0.001], + ..Default::default() + }; + assert!(!settings.exceeds(&Model::default())); + } + +} diff --git a/crates/benchup-app/src/reference_volume_gpu.rs b/crates/benchup-app/src/reference_volume_gpu.rs new file mode 100644 index 0000000..f78a08c --- /dev/null +++ b/crates/benchup-app/src/reference_volume_gpu.rs @@ -0,0 +1,79 @@ +//! GPU bounds and reconstruction parameters for per-fragment overflow tint. +use super::*; + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +pub(super) struct Parameters { + pub inverse: [[f32; 4]; 4], + pub depth: [f32; 4], + pub low: [f32; 4], + pub high: [f32; 4], +} + +impl Parameters { + pub(super) fn new(bounds: Option<(DVec3, DVec3)>, projection: (glam::DMat4, [f32; 4])) -> Self { + let Some((low, high)) = bounds else { + return bytemuck::Zeroable::zeroed(); + }; + // Reconstruct relative to the volume center; keep f64 precision until + // uploading the small uniform, without adding per-vertex attributes. + let center = (low + high) * 0.5; + Self { + inverse: (glam::DMat4::from_translation(-center) * projection.0.inverse()) + .as_mat4() + .to_cols_array_2d(), + depth: projection.1, + low: (low - center).extend(1.).as_vec4().to_array(), + high: (high - center).extend(0.).as_vec4().to_array(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn projected_overflow_reconstructs_crossing_faces_in_both_projections() { + let bounds = ( + DVec3::new(-0.128, -0.128, 0.), + DVec3::new(0.128, 0.128, 0.256), + ); + let center = (bounds.0 + bounds.1) * 0.5; + let size = DVec2::new(800., 600.); + for projection in [ + benchup_core::Projection::Perspective, + benchup_core::Projection::Parallel, + ] { + let mut camera = Camera { + projection, + ..Default::default() + }; + camera.fit(Some(bounds), size); + let (near, far) = resident::clip_planes(&camera, bounds); + let matrix = camera.matrix_with_clip_planes(size, near, far); + for remap in [false, true] { + let depth = if remap { [0.1, 0.8, 0.1, 1.] } else { [0.; 4] }; + let uniform = Parameters::new(Some(bounds), (matrix, depth)); + let inverse = glam::Mat4::from_cols_array_2d(&uniform.inverse).as_dmat4(); + for x in [-0.2, -0.128, -0.05, 0., 0.05, 0.128, 0.2] { + let point = DVec3::new(x, 0., 0.128); + let mut screen = matrix.project_point3(point).as_vec3(); + if remap { + screen.z = depth[2] + 0.8 * (screen.z - depth[0]) / depth[1]; + screen.z = depth[0] + (screen.z - depth[2]) * depth[1] / 0.8; + } + let world = inverse.project_point3(screen.as_dvec3()) + center; + assert!( + world.distance(point) < 2e-5, + "{projection:?}, remap={remap}, point={point:?}" + ); + } + } + } + assert_eq!( + Parameters::new(None, (glam::DMat4::IDENTITY, [0.; 4])).low, + [0.; 4] + ); + } +} diff --git a/crates/benchup-app/src/renderer.rs b/crates/benchup-app/src/renderer.rs index 90b22f4..d643ef7 100644 --- a/crates/benchup-app/src/renderer.rs +++ b/crates/benchup-app/src/renderer.rs @@ -13,6 +13,8 @@ mod scale_handles; pub(crate) mod agent_effects; #[path = "scene_buffers.rs"] mod scene_buffers; +#[path = "reference_volume_gpu.rs"] +mod reference_volume; use scene_buffers::GpuBuffers; pub(crate) use scale_handles::{Cache as ScaleHandleCache, paint as paint_scale_handles}; pub(crate) use resident::{CaptureScene, edited_geometry as geometry_changes, supported as resident_supported}; @@ -257,6 +259,20 @@ pub struct SceneKey { pub hover: Option, pub outliner_hover: std::collections::BTreeSet, pub erasing: std::collections::BTreeSet, + /// Viewport-only references affect clipping and replay, never model geometry. + pub reference_bounds: Option<(DVec3, DVec3)>, +} + +pub(crate) fn include_reference_bounds( + model: Option<(DVec3, DVec3)>, + reference: Option<(DVec3, DVec3)>, +) -> Option<(DVec3, DVec3)> { + match (model, reference) { + (Some((low, high)), Some((reference_low, reference_high))) => { + Some((low.min(reference_low), high.max(reference_high))) + } + (bounds, None) | (None, bounds) => bounds, + } } #[derive(Default)] @@ -295,7 +311,7 @@ pub(crate) fn scale_preview_supported(camera: &Camera, display: &benchup_core::D edit_context: model.edit_context, camera: camera.clone(), size: DVec2::ONE, pixels_per_point: 1., display: display.clone(), surface_catalog: None, dark: false, tool: benchup_core::Tool::Scale, selected: Default::default(), hover: None, - outliner_hover: Default::default(), erasing: Default::default(), + outliner_hover: Default::default(), erasing: Default::default(), reference_bounds: None, }, model, faces) } @@ -328,7 +344,8 @@ impl SceneCache { if let Some(callback) = &self.retained { painter.add(egui_wgpu::Callback::new_paint_callback( rect, - SharedScene(Arc::clone(callback), agent_effects::Projected::new(&self.agent_effects, &key.camera, rect)), + SharedScene(Arc::clone(callback), agent_effects::Projected::new(&self.agent_effects, &key.camera, rect, + key.reference_bounds, self.image_projection())), )); if let Some((_, _, annotations)) = &self.annotations { painter.extend(annotations.iter().cloned()); @@ -416,6 +433,7 @@ pub struct Mesh { pixels_per_point: f64, parallel: bool, image_depth_bounds: Option<(f64, f64)>, + reference_bounds: Option<(DVec3, DVec3)>, view: CameraView, display: benchup_core::DisplaySettings, buffer_pool: Option, @@ -478,6 +496,7 @@ impl Mesh { pixels_per_point: 1., parallel: camera.projection == benchup_core::Projection::Parallel, image_depth_bounds: None, + reference_bounds: None, view: camera.view(size), display: benchup_core::DisplaySettings::default(), buffer_pool: None, @@ -560,6 +579,9 @@ impl Mesh { } self.image_depth_bounds = lo.is_finite().then_some((lo, hi)); } + pub(crate) fn set_reference_bounds(&mut self, bounds: Option<(DVec3, DVec3)>) { + self.reference_bounds = bounds; + } fn parallel_depth_range(&self) -> Option<(f64, f64)> { let (mut lo, mut hi) = self.image_depth_bounds.unwrap_or((f64::INFINITY, f64::NEG_INFINITY)); for vertex in self.vertices.iter().chain(&self.shadow_vertices) { @@ -630,6 +652,28 @@ impl Mesh { } } } + + /// Viewport references keep their world depth, so the shared GPU depth + /// buffer hides them behind model faces and edges. Dash gaps use the same + /// fragment discard in both depth and color passes, without CPU occlusion. + pub fn reference_line(&mut self, a: DVec3, b: DVec3, width: f64, color: Color32, dashed: bool) { + let Some((a, b)) = self.section_line(a, b) else { return }; + let color = self.fog_color(color, (a + b) * 0.5); + let Some((start, end)) = self.view.segment_depth(a, b) else { return }; + let (a, b) = (start.truncate(), end.truncate()); + let delta = b - a; + let length_squared = delta.length_squared(); + if length_squared < 0.01 { return; } + let length = length_squared.sqrt(); + let normal = DVec2::new(-delta.y, delta.x) / length; + let fringe = (normal.x.abs() + normal.y.abs()) / self.pixels_per_point; + let n = normal * (width + fringe) * 0.5; + let gradient = delta * ((end.z - start.z) / length_squared); + self.emit_stroke_geometry( + &[a + n, b + n, b - n, a - n], start, gradient, a, n, color, + dashed.then_some(delta / (length * 8.)), + ); + } /// Share projections between joints on the same board, and between frames /// whose camera and stock are unchanged. Screen-space stroke width and /// scene occlusion are still resolved against the current frame. @@ -2299,8 +2343,10 @@ impl Mesh { self.edge_surfaces .retain(|_, surfaces| !surfaces.is_empty()); cache.edge_surfaces = std::mem::take(&mut self.edge_surfaces); - let effects = agent_effects::Projected::new(&cache.agent_effects, &self.joint_surfaces.camera, rect); + let camera = self.joint_surfaces.camera.clone(); + let reference_bounds = self.reference_bounds; let callback = self.retain(cache); + let effects = agent_effects::Projected::new(&cache.agent_effects, &camera, rect, reference_bounds, cache.image_projection()); painter.add(egui_wgpu::Callback::new_paint_callback( rect, SharedScene(callback, effects), @@ -3579,6 +3625,7 @@ fn create_pipeline_with_effects( fragment: Some(wgpu::FragmentState { module: shader, entry_point: Some(match (pass, effects) { + (PipelinePass::Faces, true) => "fragment_faces_effect", (PipelinePass::EdgeDepth, true) => "fragment_edge_depth_effect", (PipelinePass::ShadowFaces, true) => "fragment_shadow_faces_effect", (PipelinePass::MaterialFaces, true) => "fragment_material_faces_effect", @@ -4256,6 +4303,66 @@ mod tests { assert!(mesh.joint_surfaces.view_revision > revision, "depth changes invalidate stock-skin projections"); } + #[test] + fn reference_wireframe_survives_model_moves_in_both_projections() { + let volume = (DVec3::new(-0.128, -0.128, 0.), DVec3::new(0.128, 0.128, 0.256)); + let size = DVec2::new(900., 600.); + for projection in [benchup_core::Projection::Perspective, benchup_core::Projection::Parallel] { + let mut camera = Camera { projection, ..Default::default() }; + camera.fit(Some(volume), size); + let forward = (camera.target - camera.eye()).normalize(); + for distance in [-10., 0., 10., 100.] { + let offset = forward * camera.distance * distance; + let moved = (volume.0 + offset, volume.1 + offset); + let mut mesh = Mesh::new(&camera, size); + mesh.set_scene_clip_planes(&camera, include_reference_bounds(Some(moved), Some(volume))); + let corners: Vec<_> = (0..8).map(|bits| DVec3::new( + if bits & 1 == 0 { volume.0.x } else { volume.1.x }, + if bits & 2 == 0 { volume.0.y } else { volume.1.y }, + if bits & 4 == 0 { volume.0.z } else { volume.1.z }, + )).collect(); + for i in 0..8 { + for axis in [1, 2, 4] { + if i & axis == 0 { + mesh.reference_line(corners[i], corners[i | axis], 1.5, Color32::RED, true); + } + } + } + assert_eq!(mesh.vertices.len(), 48, "all twelve edges survive: {projection:?}, distance {distance}"); + assert_eq!(mesh.indices.len(), 72); + assert!(mesh.vertices.iter().all(|vertex| vertex.position[2] > 0. && vertex.position[2] < 1.), + "references must keep scene depth instead of drawing at the front of the viewport"); + } + let mut mesh = Mesh::new(&camera, size); + mesh.set_scene_clip_planes(&camera, include_reference_bounds(None, Some(volume))); + assert!(mesh.view.project_depth(camera.target).is_some(), "an empty model still shows its reference"); + } + } + + #[test] + fn dashed_reference_strokes_interpolate_real_depth_without_cpu_occlusion() { + let size = DVec2::splat(100.); + for projection in [benchup_core::Projection::Perspective, benchup_core::Projection::Parallel] { + let camera = Camera { projection, ..Default::default() }; + let inverse = camera.matrix(size).inverse(); + let world = |p: DVec3| inverse.project_point3(DVec3::new(p.x / 50. - 1., 1. - p.y / 50., p.z)); + let a = DVec3::new(20., 20., 0.4); + let b = DVec3::new(80., 80., 0.8); + let mut mesh = Mesh::new(&camera, size); + mesh.reference_line(world(a), world(b), 1.5, Color32::RED, true); + assert_eq!(mesh.vertices.len(), 4); + let delta = (b - a).truncate(); + for vertex in &mesh.vertices { + let p = DVec2::new(1. + f64::from(vertex.position[0]), 1. - f64::from(vertex.position[1])) * 50.; + let t = (p - a.truncate()).dot(delta) / delta.length_squared(); + let depth = a.z + (b.z - a.z) * t; + assert!((f64::from(vertex.position[2]) - depth).abs() < 2e-6); + assert!(vertex.dash_phase >= 0.); + } + assert_eq!(mesh.occlusion.polygon_queries, 0, "GPU depth handles occlusion"); + } + } + #[test] fn evaluated_snapshots_reuse_camera_frames_and_distinguish_source_edits_and_scope() { use super::*; @@ -6675,7 +6782,7 @@ mod tests { let depth_view = depth.create_view(&Default::default()); for (reverse, hybrid) in [false, true].into_iter().flat_map(|reverse| [false, true].map(|hybrid| (reverse, hybrid))) { // Depth zero is used by intentional x-ray/wireframe overlays. - for rear_depth in [0.7, 0.] { + for (rear_depth, reference) in [(0.7, false), (0., false), (0.7, true)] { let mut mesh = Mesh::new(&Camera::default(), DVec2::splat(64.)); if hybrid { mesh.enable_gpu_edge_occlusion(); } let strokes = [ @@ -6694,7 +6801,13 @@ mod tests { ]; for index in if reverse { [1, 0] } else { [0, 1] } { let (a, b, width, color) = strokes[index]; - mesh.line(a, b, width, color); + if reference && index == 1 { + let inverse = mesh.view.matrix().inverse(); + let world = |p: DVec3| inverse.project_point3(DVec3::new(p.x / 32. - 1., 1. - p.y / 32., p.z)); + mesh.reference_line(world(a), world(b), width, color, true); + } else { + mesh.line(a, b, width, color); + } } let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, @@ -6783,6 +6896,9 @@ mod tests { "selection color is preserved" ); assert!(pixel(33, 16)[1] > 0, "antialiased fringe still blends"); + if reference { + assert_eq!(pixel(32, 14), [255, 255, 255, 255], "dash gaps must not write color or depth"); + } } } } diff --git a/crates/benchup-app/src/rendering_tests.rs b/crates/benchup-app/src/rendering_tests.rs index df6905f..095bfc4 100644 --- a/crates/benchup-app/src/rendering_tests.rs +++ b/crates/benchup-app/src/rendering_tests.rs @@ -234,6 +234,29 @@ fn drawing_previews_keep_the_resident_scene_and_refresh_after_commit() { assert_eq!(app.scene_cache.resident_builds(), 1); } +#[test] +fn printer_volume_toggles_and_resizes_keep_large_scene_geometry_resident() { + let mut doc = Document::default(); + doc.model = crate::picking::tests::triangle_grid(1024); + doc.camera.fit(doc.model.bounds(), DVec2::new(800., 600.)); + let mut app = BenchUpApp::with_document(doc, None, true); + let ctx = egui::Context::default(); + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(800., 600.)); + render(&mut app, &ctx, rect); + assert_eq!(app.scene_cache.resident_builds(), 1); + for (visible, size) in [(true, [0.256; 3]), (true, [1.; 3]), (false, [1.; 3])] { + app.general_settings.volume.visible = visible; + app.general_settings.volume.size_m = size; + render(&mut app, &ctx, rect); + app.doc.camera.yaw += 0.1; + render(&mut app, &ctx, rect); + app.selected = app.doc.model.faces.keys().take(1).copied().collect(); + render(&mut app, &ctx, rect); + assert_eq!(app.scene_cache.resident_builds(), 1, "the reference must not rebuild world geometry"); + assert_eq!(app.scene_cache.mesh_builds, 0, "the reference must not send the large model through CPU projection"); + } +} + #[test] fn tape_preview_and_saved_guides_keep_the_resident_scene() { let mut doc = Document::default(); diff --git a/crates/benchup-app/src/resident_regression.rs b/crates/benchup-app/src/resident_regression.rs index 55a8745..4a11938 100644 --- a/crates/benchup-app/src/resident_regression.rs +++ b/crates/benchup-app/src/resident_regression.rs @@ -20,6 +20,7 @@ impl SceneCache { hover: None, outliner_hover: Default::default(), erasing: Default::default(), + reference_bounds: None, }; shadows::validate(&key, doc.model.bounds().ok_or("Empty scene")?) } @@ -136,6 +137,7 @@ impl SceneCache { hover: None, outliner_hover: Default::default(), erasing: Default::default(), + reference_bounds: None, }; let mut failure = None; let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { diff --git a/crates/benchup-app/src/resident_scene.rs b/crates/benchup-app/src/resident_scene.rs index a6664a9..85d9855 100644 --- a/crates/benchup-app/src/resident_scene.rs +++ b/crates/benchup-app/src/resident_scene.rs @@ -85,6 +85,8 @@ struct Uniform { scale_pivot: [f32; 4], scale_factors: [f32; 4], agent_effect: [f32; 4], + volume_low: [f32; 4], + volume_high: [f32; 4], } #[derive(Default)] pub(super) struct Cache { @@ -171,7 +173,7 @@ fn geometry_key(key: &SceneKey) -> SceneKey { edit_context: None, camera: Camera::default(), size: DVec2::ZERO, pixels_per_point: 1., display: key.display.clone(), surface_catalog: key.surface_catalog.clone(), dark: key.dark, tool: benchup_core::Tool::Orbit, selected: Default::default(), hover: None, - outliner_hover: Default::default(), erasing: Default::default(), + outliner_hover: Default::default(), erasing: Default::default(), reference_bounds: None, }; key.display.group_emphasis = false; // Reference overlays are submitted separately from the retained geometry. @@ -631,12 +633,9 @@ impl SceneCache { ) { let geometry = Arc::clone(self.resident.geometry.as_ref().unwrap()); let source_bounds = self.resident.bounds.unwrap_or(geometry.bounds); - let bounds = self.scale_transform.map_or(source_bounds, |scale| { - let a = scale.pivot + (source_bounds.0 - scale.pivot) * scale.factors; - let b = scale.pivot + (source_bounds.1 - scale.pivot) * scale.factors; - (source_bounds.0.min(a), source_bounds.1.max(b)) - }); - let (near, far) = clip_planes(&key.camera, bounds); + let bounds = scaled_scene_bounds(source_bounds, self.scale_transform); + let clip_bounds = include_reference_bounds(Some(bounds), key.reference_bounds).unwrap(); + let (near, far) = clip_planes(&key.camera, clip_bounds); let matrix = key.camera.matrix_with_clip_planes(key.size, near, far) * glam::DMat4::from_translation(geometry.origin); self.image_matrix = Some(key.camera.matrix_with_clip_planes(key.size, near, far)); @@ -723,6 +722,10 @@ impl SceneCache { scale_factors: self.scale_transform.map_or([1.; 4], |scale| scale.factors.extend(0.).as_vec4().to_array()), agent_effect: self.agent_effects.parameters(&key.camera, rect), + volume_low: key.reference_bounds.map_or([0.; 4], |(low, _)| + (low - geometry.origin).extend(1.).as_vec4().to_array()), + volume_high: key.reference_bounds.map_or([0.; 4], |(_, high)| + (high - geometry.origin).extend(0.).as_vec4().to_array()), flags: [ 0., if key.camera.projection == benchup_core::Projection::Parallel { @@ -762,6 +765,14 @@ pub(super) fn clip_planes(camera: &Camera, bounds: (DVec3, DVec3)) -> (f64, f64) (near, far) } +fn scaled_scene_bounds(bounds: (DVec3, DVec3), scale: Option) -> (DVec3, DVec3) { + scale.map_or(bounds, |scale| { + let a = scale.pivot + (bounds.0 - scale.pivot) * scale.factors; + let b = scale.pivot + (bounds.1 - scale.pivot) * scale.factors; + (bounds.0.min(a).min(b), bounds.1.max(a).max(b)) + }) +} + impl Geometry { #[cfg(test)] fn new( @@ -1469,7 +1480,9 @@ impl SceneCache { |(lo, hi), p| (lo.min(p), hi.max(p)), ) }); - let (near, far) = clip_planes(&key.camera, bounds); + let bounds = scaled_scene_bounds(bounds, self.scale_transform); + let clip_bounds = include_reference_bounds(Some(bounds), key.reference_bounds).unwrap(); + let (near, far) = clip_planes(&key.camera, clip_bounds); let mut mesh = Mesh::new(&key.camera, key.size); mesh.view = key.camera.view_with_clip_planes(key.size, near, far); mesh.set_pixels_per_point(key.pixels_per_point); @@ -1603,6 +1616,7 @@ mod tests { hover: None, outliner_hover: Default::default(), erasing: Default::default(), + reference_bounds: None, } } @@ -2313,4 +2327,30 @@ mod tests { let inside = (camera.eye() - DVec3::ONE, camera.eye() + DVec3::ONE); assert_eq!(clip_planes(&camera, inside).0, 0.005); } + + #[test] + fn resident_reference_mesh_keeps_the_volume_when_geometry_moves_away() { + let volume = (DVec3::new(-0.128, -0.128, 0.), DVec3::new(0.128, 0.128, 0.256)); + let cache = SceneCache::default(); + for projection in [benchup_core::Projection::Perspective, benchup_core::Projection::Parallel] { + let mut key = key(); + key.reference_bounds = Some(volume); + key.camera.projection = projection; + key.camera.fit(Some(volume), key.size); + let mut model = model(1024); + let offset = (key.camera.target - key.camera.eye()).normalize() * 10000.; + for vertex in model.vertices.values_mut() { + vertex.position += offset; + } + let references = cache.resident_reference_mesh(&key, &model); + for x in [volume.0.x, volume.1.x] { + for y in [volume.0.y, volume.1.y] { + for z in [volume.0.z, volume.1.z] { + let p = references.view.project_depth(DVec3::new(x, y, z)).unwrap(); + assert!((0. ..=1.).contains(&p.z), "reference corner clipped in {projection:?}"); + } + } + } + } + } } diff --git a/crates/benchup-app/src/resident_scene.wgsl b/crates/benchup-app/src/resident_scene.wgsl index 88f8e48..bd20de5 100644 --- a/crates/benchup-app/src/resident_scene.wgsl +++ b/crates/benchup-app/src/resident_scene.wgsl @@ -21,6 +21,8 @@ struct Camera { scale_pivot: vec4, scale_factors: vec4, agent_effect: vec4, + volume_low: vec4, + volume_high: vec4, } @group(0) @binding(0) var camera: Camera; @group(0) @binding(1) var interaction_states: texture_2d; @@ -78,6 +80,7 @@ struct FaceOutput { @location(8) clip: vec3, @location(5) grain: vec3, @location(6) @interpolate(flat) finish: vec4, + @location(9) world: vec3, } fn target_color(color: vec4) -> vec4 { if camera.flags.x == 0.0 { return color; } @@ -117,6 +120,7 @@ fn surface_vertex(position: vec3, normal: vec3, anchor: vec3, col let shaded = vec4(floor(material.rgb * brightness * 255.0 + vec3(0.5)) / 255.0, material.a); var output: FaceOutput; output.position = camera.matrix * vec4(preview_point(position,state),1.0); + output.world = preview_point(position,state); if ((state&64u)!=0u && (camera.interaction.w&4u)==0u) || (camera.interaction.y!=0u && (state&4u)==0u) {output.position=vec4(2.0,2.0,2.0,1.0);} output.stamp = agent_stamp(interaction); output.clip = output.position.xyw; @@ -189,7 +193,8 @@ fn face_color(input: FaceOutput) -> @location(0) vec4 { let amount = shadow_coverage(input); let dark = floor(input.color.rgb * (1.0-camera.shadow_params.x) * 255.0 + vec3(0.5))/255.0; let rgb = mix(input.color.rgb,dark,amount); - return target_color(agent_color(vec4(rgb, input.color.a), input.stamp, input.clip)); + let color = agent_color(vec4(rgb, input.color.a), input.stamp, input.clip); + return reference_overflow_tint(target_color(color), input.world, camera.volume_low, camera.volume_high, camera.flags.x != 0.0); } @fragment fn material_color(input: FaceOutput) -> @location(0) vec4 { @@ -197,7 +202,8 @@ fn material_color(input: FaceOutput) -> @location(0) vec4 { let dark = floor(input.color.rgb * (1.0-camera.shadow_params.x) * 255.0 + vec3(0.5))/255.0; let rgb = mix(input.color.rgb,dark,amount); let finish = vec4(input.finish.xyz, input.finish.w * (1.0 - amount * camera.shadow_params.x)); - return target_color(agent_color(vec4(finish_color(rgb, input.color.a, input.grain, finish), input.color.a), input.stamp, input.clip)); + let color = agent_color(vec4(finish_color(rgb, input.color.a, input.grain, finish), input.color.a), input.stamp, input.clip); + return reference_overflow_tint(target_color(color), input.world, camera.volume_low, camera.volume_high, camera.flags.x != 0.0); } // Offset depth only across the actual incident face, never its extension past // a silhouette. Using homogeneous planes also works at near-plane crossings. diff --git a/crates/benchup-app/src/settings.rs b/crates/benchup-app/src/settings.rs index 36bd500..829dad3 100644 --- a/crates/benchup-app/src/settings.rs +++ b/crates/benchup-app/src/settings.rs @@ -207,6 +207,7 @@ pub(super) struct GeneralSettings { pub auto_group_new_shapes: bool, pub show_fps: bool, pub default_units: benchup_core::UnitSettings, + pub volume: super::printer_volume::Settings, pub tool_keys: Vec, pub stock: stock_settings::Settings, pub export_scale: export_scale::Preferences, @@ -232,6 +233,7 @@ impl Default for GeneralSettings { auto_group_new_shapes: false, show_fps: false, default_units: Default::default(), + volume: Default::default(), stock: Default::default(), export_scale: Default::default(), agent: Default::default(), @@ -297,6 +299,7 @@ impl GeneralSettings { self.space_mouse.normalize(); self.stock.normalize(); self.export_scale.normalize(); + self.volume.sanitize(); self.agent.normalize(); // Earlier builds saved bare codes; every catalog now uses language_REGION. match self.language.as_str() { @@ -765,11 +768,20 @@ impl BenchUpApp { } }); } + let reference_label = tr!("settings.toggle_reference_volume"); + if reference_label.to_lowercase().contains(&query) { + matches += 1; + table.row(ui, "settings_volume_hotkey", |column, ui| { + if column == 0 { ui.text_label(reference_label); } + else { self.reference_volume_shortcut(ui); } + }); + } if matches == 0 { ui.text_weak(tr!("settings.no_tools_match_your_search")); } if ui.button(tr!("settings.restore_default_shortcuts")).clicked() { self.general_settings.tool_keys = GeneralSettings::default().tool_keys; + self.general_settings.volume.hotkey = None; } } Section::Units => { @@ -850,6 +862,45 @@ fn color_row(ui: &mut egui::Ui, label: &str, color: &mut [u8; 3]) { #[cfg(test)] mod tests { + #[test] + fn printer_volume_persists_and_defaults_for_older_saves() { + // Preferences saved before this feature must still load. + let older: GeneralSettings = serde_json::from_str("{}").unwrap(); + assert_eq!( + older.volume, + printer_volume::Settings::default(), + "missing volume settings fall back to the defaults" + ); + + let mut settings = GeneralSettings::default(); + settings.volume.visible = true; + settings.volume.size_m = [0.3, 0.25, 0.4]; + settings.volume.hotkey = Some("V".into()); + + let saved = serde_json::to_string(&settings).unwrap(); + let restored: GeneralSettings = serde_json::from_str(&saved).unwrap(); + assert!(restored.volume.visible); + assert_eq!(restored.volume.size_m, [0.3, 0.25, 0.4]); + assert_eq!(restored.volume.hotkey.as_deref(), Some("V")); + } + + #[test] + fn normalize_keeps_valid_volume_and_clamps_damaged_values() { + let mut settings = GeneralSettings::default(); + // A zero width is repaired, a non-finite depth falls back, an absurd + // height clamps: each axis is handled independently. + settings.volume.size_m = [0., f64::INFINITY, 1e12]; + settings.normalize(); + assert_eq!( + settings.volume.size_m, + [ + printer_volume::MIN_M, + printer_volume::Settings::default().size_m[1], + printer_volume::MAX_M + ] + ); + } + fn rendered_text(shapes: &[egui::epaint::ClippedShape]) -> Vec { fn collect(shape: &egui::Shape, text: &mut Vec) { match shape { @@ -1325,4 +1376,70 @@ mod tests { assert!(text.iter().any(|label| label == "Language")); assert!(text.iter().any(|label| label == "English")); } + #[test] + fn legacy_toolbar_preferences_keep_reference_volume_visibility_and_shortcut() { + let mut settings: GeneralSettings = serde_json::from_str( + r#"{"volume":{"show_button":false,"visible":true,"size_m":[0.3,0.2,0.1],"hotkey":"V"}}"#, + ).unwrap(); + settings.normalize(); + assert!(settings.volume.visible); + assert_eq!(settings.volume.size_m, [0.3, 0.2, 0.1]); + assert_eq!(settings.volume.hotkey.as_deref(), Some("V")); + assert!(!serde_json::to_string(&settings.volume).unwrap().contains("show_button")); + } + + #[test] + fn reference_volume_shortcut_has_a_searchable_name_and_leaves_tool_settings() { + let ctx = egui::Context::default(); + let mut app = BenchUpApp::with_document(Document::default(), None, true); + app.general_settings.section = Section::Tools; + let output = ctx.run_test_ui(egui::RawInput::default(), |ui| app.settings_contents(ui)); + let text = rendered_text(&output.shapes); + assert!(!text.iter().any(|label| label == tr!("settings.printer_and_tool_volume"))); + assert!(!text.iter().any(|label| label == tr!("settings.width_x"))); + + app.general_settings.section = Section::Shortcuts; + app.shortcut_filter = "reference volume".into(); + app.general_settings.volume.hotkey = Some("V".into()); + let output = ctx.run_test_ui(egui::RawInput::default(), |ui| app.settings_contents(ui)); + let text = rendered_text(&output.shapes); + assert!(text.iter().any(|label| label == tr!("settings.toggle_reference_volume"))); + assert!(text.iter().any(|label| label == "V")); + assert!(!text.iter().any(|label| label == tr!("settings.no_tools_match_your_search"))); + } + + #[test] + fn every_printer_volume_label_is_translated_in_all_catalogs() { + const CATALOGS: [(&str, &str); 6] = [ + ("en_US", include_str!("../../../assets/i18n/en_US.json")), + ("es_419", include_str!("../../../assets/i18n/es_419.json")), + ("it_IT", include_str!("../../../assets/i18n/it_IT.json")), + ("pt_BR", include_str!("../../../assets/i18n/pt_BR.json")), + ("vi_VN", include_str!("../../../assets/i18n/vi_VN.json")), + ("zh_CN", include_str!("../../../assets/i18n/zh_CN.json")), + ]; + const KEYS: [&str; 10] = [ + "app.show_or_hide_the_printer_or_tool_volume", + "app.the_model_is_outside_the_printer_or_tool_volume", + "settings.printer_and_tool_volume", + "settings.a_locked_reference_box_for_a_printer_s_build", + "settings.width_x", + "settings.depth_y", + "settings.height_z", + "settings.clear_the_toggle_shortcut", + "reference_volume.show", + "settings.toggle_reference_volume", + ]; + for (language, raw) in CATALOGS { + let catalog: serde_json::Value = serde_json::from_str(raw).unwrap(); + for key in KEYS { + let text = catalog + .get(key) + .and_then(|value| value.as_str()) + .unwrap_or_else(|| panic!("{language} is missing {key}")); + assert!(!text.trim().is_empty(), "{language} has an empty {key}"); + } + } + } + } diff --git a/crates/benchup-app/src/sidebar.rs b/crates/benchup-app/src/sidebar.rs index a65db6e..ad0fb56 100644 --- a/crates/benchup-app/src/sidebar.rs +++ b/crates/benchup-app/src/sidebar.rs @@ -201,6 +201,26 @@ mod guide_preference_tests { } } + #[test] + fn reference_volume_menu_options_save_without_model_edits() { + let ctx = egui::Context::default(); + let mut storage = Storage::default(); + let mut app = BenchUpApp::with_document(Document::default(), None, true); + for visible in [true, false] { + app.general_settings.volume.visible = visible; + app.general_settings.volume.size_m = [0.3, 0.2, 0.4]; + app.general_settings.volume.hotkey = Some("V".into()); + storage.flushed = false; + app.persist_inspector_changes(&ctx, Some(&mut storage), false); + assert!(storage.flushed); + assert!(!app.project.modified); + assert!(app.dirty_since.is_none()); + let mut restored = BenchUpApp::with_document(Document::default(), None, true); + restored.restore_inspector_preferences(&egui::Context::default(), Some(&storage)); + assert_eq!(restored.general_settings.volume, app.general_settings.volume); + } + } + #[test] fn tool_rail_separators_default_and_restore_without_model_edits() { let legacy: InspectorPreferences = serde_json::from_str("{}").unwrap(); @@ -5880,6 +5900,7 @@ impl BenchUpApp { } ui.separator(); self.sections_menu(ui); + self.reference_volume_menu(ui); } fn display_contents(&mut self, ui: &mut egui::Ui) { diff --git a/crates/benchup-app/src/surface_appearance.wgsl b/crates/benchup-app/src/surface_appearance.wgsl index d440e17..d540ff0 100644 --- a/crates/benchup-app/src/surface_appearance.wgsl +++ b/crates/benchup-app/src/surface_appearance.wgsl @@ -1,5 +1,25 @@ // Shared by the retained world renderer and the clipped/annotation renderer. // Coordinates are in metres: part space for wood, face-plane space for glue. +// A translucent warning coat is evaluated per fragment, never per object or +// triangle. Keep the original face alpha and let its material remain visible. +fn reference_overflow_color(point: vec3, low: vec4, high: vec4) -> vec4 { + if low.w == 0.0 { return vec4(0.0); } + let tolerance = max((high.xyz - low.xyz) * 0.000001, vec3(0.0000001)); + if all(point >= low.xyz - tolerance) && all(point <= high.xyz + tolerance) { + return vec4(0.0); + } + return vec4(vec3(1.0, 0.12, 0.08) * 0.35, 0.35); +} +fn reference_overflow_tint(color: vec4, point: vec3, low: vec4, high: vec4, linear_target: bool) -> vec4 { + if low.w == 0.0 { return color; } + var warning = reference_overflow_color(point, low, high); + if warning.a == 0.0 { return color; } + if linear_target { + warning = vec4(finish_srgb_to_linear(warning.rgb / max(warning.a, 0.000001)) * warning.a, warning.a); + } + return vec4(color.rgb * (1.0 - warning.a) + warning.rgb * color.a, color.a); +} + fn finish_color(rgb: vec3, alpha: f32, p: vec3, finish: vec4) -> vec3 { return finish_color_with_derivatives(rgb, alpha, p, finish, dpdx(p.xy), dpdy(p.xy), fwidth(p)); } diff --git a/docs/cli.md b/docs/cli.md index 6a179ce..7e6aabe 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -85,7 +85,7 @@ agent ──MCP (stdio) or benchup … --live──▶ benchup bridge (127.0.0.1 ``` 1. In BenchUp, open **Settings → Agent connection** and turn on **Allow agent connection**. It is off by default; the setting is remembered. -2. Copy the pairing token shown there (or one of the setup snippets) and give it to the agent as `BENCHUP_AGENT_TOKEN`. The token stays on that device; **New token** replaces it and disconnects agents that use the old one. +2. Copy the pairing token shown there (or one of the setup snippets) and give it to the agent as `BENCHUP_AGENT_TOKEN`. The token stays on that device; **Refresh token** asks for confirmation before replacing it and disconnecting agents that use the old one. 3. Connect the agent: ```sh diff --git a/docs/controls.md b/docs/controls.md index f997e1a..1d06b34 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -64,6 +64,8 @@ Orbiting always uses the combined bounding-box center of all objects, including ## Views and cameras +View → Reference volume, below Sections, controls a fixed reference box and its width (X), depth (Y), and height (Z) in the workspace's length units. The box is centered on the origin with its base at Z = 0. Face portions beyond its bounds receive a transparent red tint and trigger a warning. The box and its dimensions are remembered across projects and are never selectable or exported. Assign or clear **Toggle reference volume** in Settings → Shortcuts management; it is unassigned by default. + Click an axis label on the compass to look along it: −Y is the Front view, +X Right, +Y Back, −X Left, +Z Top, and −Z Bottom. The front of a model faces −Y. The sidebar's **Camera** section chooses Perspective or Parallel (orthographic) projection, sets the field of view in perspective (15–100°), and offers **Fit model**, **Fit selection**, and **Reset camera**. The tabs above the viewport are views of the same model. Each view keeps its own camera, while the model, selection, and undo history are shared; tools act in the active view. Click **+** to add a view that starts from the current camera. Drag a tab to an edge of a viewport to split the workspace, or to its center to stack it there as a tab. Right-click a tab to rename or close it; the last view cannot be closed. Each view's camera is saved in the project file. The layout, view names, and the active view are application preferences, so they are remembered across restarts but do not travel with the file. diff --git a/scripts/benchmark_viewport_web.mjs b/scripts/benchmark_viewport_web.mjs index d521244..5690613 100644 --- a/scripts/benchmark_viewport_web.mjs +++ b/scripts/benchmark_viewport_web.mjs @@ -748,8 +748,8 @@ fn test_sun_fragment(value: FaceOutput) -> @location(0) vec4 { const bits=new Uint32Array(32*32*2),f=new Float32Array(1),u=new Uint32Array(f.buffer); for(let y=0;y<32;y++)for(let x=0;x<16;x++){const i=(y*32+x)*2;bits[i]=11;f[0]=.3+.4*(x+.5)/32;bits[i+1]=u[0];} device.queue.writeTexture({texture:sunlight},bits,{bytesPerRow:256},[32,32]); - const uniform=device.createBuffer({size:496,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}); - const camera=new Float32Array(124);camera[32]=.35;camera[34]=.000002; + const uniform=device.createBuffer({size:528,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}); + const camera=new Float32Array(132);camera[32]=.35;camera[34]=.000002; const bind0=device.createBindGroup({layout:pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:uniform}}]}); const bind1=device.createBindGroup({layout:pipeline.getBindGroupLayout(1),entries:[{binding:1,resource:sunlight.createView()}]}); const target=device.createTexture({size:[8,1],format:'rgba8unorm',usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}); @@ -834,8 +834,8 @@ async function validateMarkers(shader) { const vertices=device.createBuffer({size:values.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});device.queue.writeBuffer(vertices,0,values); const states=device.createTexture({size:[512,1],format:'r32uint',usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST}); const flags=new Uint32Array(512);flags[1]=1;flags[3]=65;flags[4]=1;device.queue.writeTexture({texture:states},flags,{bytesPerRow:2048},[512,1]); - const uniform=device.createBuffer({size:496,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}); - const camera=new Float32Array(124);for(let i=0;i<4;i++)camera[i*5]=1;camera.set([64,64,1,1.8],64);camera.set([1,0,0,1],88);camera.set([1,1,1,1],108); + const uniform=device.createBuffer({size:528,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}); + const camera=new Float32Array(132);for(let i=0;i<4;i++)camera[i*5]=1;camera.set([64,64,1,1.8],64);camera.set([1,0,0,1],88);camera.set([1,1,1,1],108); const bind=device.createBindGroup({layout:pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:uniform}},{binding:1,resource:states.createView()}]}); const target=device.createTexture({size:[64,64],format:'rgba8unorm',usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}); const readback=device.createBuffer({size:16384,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}); diff --git a/scripts/test_agent_effects.mjs b/scripts/test_agent_effects.mjs index b0c5501..a72d405 100644 --- a/scripts/test_agent_effects.mjs +++ b/scripts/test_agent_effects.mjs @@ -75,7 +75,7 @@ async function validate(sources) { const projectedLayout=device.createBindGroupLayout({entries:[ {binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:'float'}}, {binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:'filtering'}}, - {binding:2,visibility:GPUShaderStage.FRAGMENT,buffer:{type:'uniform',minBindingSize:32}} + {binding:2,visibility:GPUShaderStage.FRAGMENT,buffer:{type:'uniform',minBindingSize:144}} ]}); const projectedPipelineLayout=device.createPipelineLayout({bindGroupLayouts:[projectedLayout]}); for(const srgb of [false,true])for(const effects of [false,true]){ @@ -91,6 +91,36 @@ async function validate(sources) { ])await make(modules['resident_scene.wgsl'],vertex,fragment,buffers,format); const robot=await make(modules['agent_robot.wgsl'],'robot_vertex','robot_color',[]); const departing=await make(modules['agent_robot.wgsl'],'ghost_vertex','ghost_color',[ghost]); + const overflowFaces=await make(modules['edges.wgsl'],'vertex_main','fragment_faces_effect',[compact],'rgba8unorm',projectedPipelineLayout); + // Sample the shared overflow shader across all six boundaries, including + // points on the boundary and inside the very same crossing face. + const positions=[[0,0,.128],[-.128,0,.128],[.128,0,.128],[0,-.128,.128],[0,.128,.128],[0,0,0],[0,0,.256], + [-.2,0,.128],[.2,0,.128],[0,-.2,.128],[0,.2,.128],[0,0,-.02],[0,0,.3],[-.05,0,.128],[.05,0,.128]]; + const overflowProbe=device.createShaderModule({code:sources['surface_appearance.wgsl']+` + @group(0) @binding(0) var samples: array>; + @compute @workgroup_size(1) fn probe(@builtin(global_invocation_id) id:vec3) { + let points=array,${positions.length}>(${positions.map(p=>`vec3(${p.join(',')})`).join(',')}); + let low=vec4(-.128,-.128,0.0,1.0);let high=vec4(.128,.128,.256,0.0); + let color=reference_overflow_color(points[id.x],low,high); + let tinted=reference_overflow_tint(vec4(.2,.3,.4,.6),points[id.x],low,high,false); + let disabled=reference_overflow_color(points[id.x],vec4(low.xyz,0.0),high); + samples[id.x]=vec4(color.a,tinted.a,tinted.r,disabled.a); + }`}); + const overflowPipeline=await device.createComputePipelineAsync({layout:'auto',compute:{module:overflowProbe,entryPoint:'probe'}}); + const overflowOutput=device.createBuffer({size:positions.length*16,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}); + const overflowRead=device.createBuffer({size:positions.length*16,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}); + const overflowBind=device.createBindGroup({layout:overflowPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:overflowOutput}}]}); + const overflowEncoder=device.createCommandEncoder(),overflowPass=overflowEncoder.beginComputePass(); + overflowPass.setPipeline(overflowPipeline);overflowPass.setBindGroup(0,overflowBind);overflowPass.dispatchWorkgroups(positions.length);overflowPass.end(); + overflowEncoder.copyBufferToBuffer(overflowOutput,0,overflowRead,0,positions.length*16);device.queue.submit([overflowEncoder.finish()]); + await overflowRead.mapAsync(GPUMapMode.READ);const overflowValues=new Float32Array(overflowRead.getMappedRange()); + for(let i=0;i=7&&i<=12; + for(const [column,expected] of [[0,outside ? .35 : 0],[1,.6],[2,outside ? .34 : .2],[3,0]]){ + if(Math.abs(overflowValues[i*4+column]-expected)>1e-5)throw Error(`Reference overflow differs at ${i}:${column}`); + } + } + overflowRead.unmap();overflowOutput.destroy();overflowRead.destroy(); const W=192,H=192; const capture=async(pipeline,bind,vertices=null,count=6)=>{ const image=device.createTexture({size:[W,H],format:'rgba8unorm',usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}); @@ -121,7 +151,8 @@ async function validate(sources) { const base=i*32;dv.setFloat32(base,p[0],true);dv.setFloat32(base+4,p[1],true);dv.setFloat32(base+8,.5,true); [145,160,174,255].forEach((v,j)=>dv.setUint8(base+12+j,v));dv.setFloat32(base+24,-1,true);dv.setFloat32(base+28,10,true); } - const geometry=buffer(data,GPUBufferUsage.VERTEX),effectData=new Float32Array([10,-1,0,1,W,H,1,0]); + const geometry=buffer(data,GPUBufferUsage.VERTEX),effectData=new Float32Array(36); + effectData.set([10,-1,0,1,W,H,1,0]); const effectUniform=buffer(effectData,GPUBufferUsage.UNIFORM); const empty=device.createTexture({size:[1,1],format:'rgba8unorm',usage:GPUTextureUsage.TEXTURE_BINDING}); const effectBind=device.createBindGroup({layout:projectedLayout,entries:[{binding:0,resource:empty.createView()},{binding:1,resource:device.createSampler()},{binding:2,resource:{buffer:effectUniform}}]}); @@ -158,9 +189,23 @@ async function validate(sources) { dissolveCoverage.push(image.reduce((n,v,i)=>n+Number(i%4===3&&v>0),0)/(W*H)); } if(dissolveCoverage[0]<.99||dissolveCoverage[1]<.35||dissolveCoverage[1]>.65||dissolveCoverage[2]!==0)throw Error('Incorrect digital dissolve: '+dissolveCoverage); + effectData.fill(0);effectData.set([20,-1,0,1,W,H,0,0]); + for(let i=0;i<4;i++)effectData[8+i*5]=1; + effectData.set([-.25,-.25,0,1],28);effectData.set([.25,.25,1,0],32); + device.queue.writeBuffer(effectUniform,0,effectData); + const overflowImage=await capture(overflowFaces,effectBind,geometry,3);samples.push(overflowImage); + const pixel=(image,x,y)=>Array.from(image.slice((y*W+x)*4,(y*W+x)*4+4)); + const expect=(actual,expected,label)=>{if(actual.some((v,i)=>Math.abs(v-expected[i])>2))throw Error(label+': '+actual)}; + expect(pixel(overflowImage,W/2,H/2),[145,160,174,255],'inside portion of crossing face'); + expect(pixel(overflowImage,W/8,H/2),[184,115,120,255],'overflowing portion of crossing face'); + const unaffectedEdges=await capture(assembly,effectBind,geometry,3); + expect(pixel(unaffectedEdges,W/8,H/2),[145,160,174,255],'edges retain their original color'); + effectData[31]=0;device.queue.writeBuffer(effectUniform,0,effectData); + const hiddenVolume=await capture(overflowFaces,effectBind,geometry,3); + expect(pixel(hiddenVolume,W/8,H/2),[145,160,174,255],'hiding the volume removes its tint'); const sheet=new OffscreenCanvas(W*5,(H+32)*Math.ceil(samples.length/5)),ctx=sheet.getContext('2d'); ctx.fillStyle='#101820';ctx.fillRect(0,0,sheet.width,sheet.height);ctx.font='14px sans-serif';ctx.fillStyle='#d9f8ff'; - const captions=['Looking / 0.2s','Looking / 1.1s','Preparing / 0.2s','Preparing / 0.8s','Reveal / start','Reveal / half','Reveal / complete','Scan / bottom','Scan / top','Scan / bottom','Scan / top','Dissolve / start','Dissolve / half','Dissolve / complete']; + const captions=['Looking / 0.2s','Looking / 1.1s','Preparing / 0.2s','Preparing / 0.8s','Reveal / start','Reveal / half','Reveal / complete','Scan / bottom','Scan / top','Scan / bottom','Scan / top','Dissolve / start','Dissolve / half','Dissolve / complete','Reference overflow']; for(const [i,bytes] of samples.entries()){ const pixels=bytes.slice();for(let j=0;j{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.readAsDataURL(blob)}); const error=await device.popErrorScope();if(error)throw Error(error.message); - return {passed:true,shader_modules:3,pipelines:pipelineCount,eye_motion_pixels:eyeMotion,gear_motion_pixels:gearMotion,reveal_coverage:coverage,dissolve_coverage:dissolveCoverage,scan_rows:scanRows,adapter:adapter.info.vendor,preview}; + return {passed:true,shader_modules:4,pipelines:pipelineCount,overflow_samples:positions.length,eye_motion_pixels:eyeMotion,gear_motion_pixels:gearMotion,reveal_coverage:coverage,dissolve_coverage:dissolveCoverage,scan_rows:scanRows,adapter:adapter.info.vendor,preview}; }finally{device.destroy()} }