From 57257eaecd2f121a8a393ed5b8a3419db739433a Mon Sep 17 00:00:00 2001 From: selune <35337584+0xlillith@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:25:53 +0100 Subject: [PATCH] chore: preserve reviewed CPU directional-shadow UI source checkpoint --- proposals/render/2026-10-30/README.md | 6 +- .../cpu-directional-shadow-ui/README.md | 19 + .../pending/cpu-directional-shadow-ui.json | 47 + .../ui-egui/src/render_workspace_cpu.rs | 856 ++ .../ui-egui/src/render_workspace_materials.rs | 1196 ++ .../ui-egui/src/render_workspace_tests.rs | 11297 ++++++++++++++++ .../cpu-directional-shadow-ui/delta.patch | 327 + .../source-bindings.json | 56 + 8 files changed, 13803 insertions(+), 1 deletion(-) create mode 100644 proposals/render/2026-10-31/cpu-directional-shadow-ui/README.md create mode 100644 proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/assets/locales/pending/cpu-directional-shadow-ui.json create mode 100644 proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_cpu.rs create mode 100644 proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_materials.rs create mode 100644 proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_tests.rs create mode 100644 proposals/render/2026-10-31/cpu-directional-shadow-ui/delta.patch create mode 100644 proposals/render/2026-10-31/cpu-directional-shadow-ui/source-bindings.json diff --git a/proposals/render/2026-10-30/README.md b/proposals/render/2026-10-30/README.md index aa1914634..ebb4fc177 100644 --- a/proposals/render/2026-10-30/README.md +++ b/proposals/render/2026-10-30/README.md @@ -196,4 +196,8 @@ The complete API consumer connects captured direct visibility and RGB shading to ### 31 October — C23 quality budget controls and minimal TIR test-call adapter -[Three-path source and exact delta](../2026-10-31/c23-three-path-source/README.md). Existing GPU review/acknowledgement/currentness/save preserved;74old inspector tests and original TIR oracles retained,7newUI tests UNRUN. No universal CPU/Raster quality presets, compilation, native/GPU/full-CI or readiness claim. +[Three-path source and exact delta](../2026-10-31/c23-three-path-source/README.md). Existing GPU review/acknowledgement/currentness/save preserved;74old inspector tests and original TIR oracles retained,7newUI tests UNRUN. No universal CPU/Raster quality presets, compilation, native/GPU/full-CI or readiness claim. + +### 31 October — CPU glass directional-shadow UI bridge + +[Four-path source and request-boundary documentation](../2026-10-31/cpu-directional-shadow-ui/README.md). UniformON/OFF reaches the existing producer; mixed assignments refuse explicitly. Original277cases retained, one old unsupported-feature frontier deliberately updated,7newcasesUNRUN. Included in C23source only, not native/image/GPU/full-CI qualification. diff --git a/proposals/render/2026-10-31/cpu-directional-shadow-ui/README.md b/proposals/render/2026-10-31/cpu-directional-shadow-ui/README.md new file mode 100644 index 000000000..306e4d230 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-directional-shadow-ui/README.md @@ -0,0 +1,19 @@ +# CPU glass editor to directional transmitted-shadow request + +Reviewed source checkpoint for #6201, now included in the seven-path C23 candidate. It is unformatted, uncompiled and unrun; it is not an installed-app fix, a passing GPU/native/full-CI result, or general feature parity. The exact receiver was C22 post-format source manifest9b193a92875783101d2511342eb4e4781abeb2f149187179f8900931fbd06e3f. The full adopted C23 source manifest is55bcda795f1c124465330f9156ad6894501ac1e184203fe3e2994d1052eee45b (3,582members); production PR #8938 still has its original head. + +## User-visible request behavior + +For active, current whole-body glass bindings with explicit CPU permission, uniform transmitted-shadow choices now reach the existing directional RGB producer: all ON derives directional_shadow_transmission=true in the submitted wire; all OFF preserves false/omission. The authored editor-global default remains false. The current producer has one global switch, so mixed ON/OFF or OFF/ON refuses explicitly instead of dropping an OFF assignment. An incoming conflicting global true also refuses. Direct manual authoring of that global View field remains subject to the earlier CPU composition validation; this bridge does not promise a new global-authoring route. + +Global shadows, environment/nesting restrictions, all currentness/duplicate/stable-identity/visibility/permission checks, ThinSheet/ClosedBox boundaries and real producer certification/admission/resource/work/cancellation gates remain in force. Unsupported coat/maps/subsurface remain refused. The UI commits only a completely validated request; no failed composition mutates the authored design or request payload. No CPU permission, boundary, backend, preset, depth or cap is silently changed. + +The admitted effect is straight directional RGB attenuation through the currently certified, finite supported geometry, not bent refracted shadows, caustics, arbitrary closed meshes, environment transport or per-body shadow-mask parity. Unselected geometry still blocks according to the producer. New localized help states this partial boundary. + +## Original acceptance and remaining validation + +The existing277 test bodies in render_workspace_tests.rs are byte-preserved, with seven new original cases. One explicitly authorized old expectation in the existing CPU native-style harness is changed because it asserted that CPU transmitted shadows were always unsupported: the SAME fixture, IOR1, policy and controls now require the correct typed/wire flag and real render.preflight success. Its prior function is preserved privately, and all other bytes/refusals remain unchanged. This is a deliberate new-feature boundary, not adapting an image oracle or weakening a threshold. + +New cases cover two-body uniform selections across fixed/progressive and transport policies, both mixed orders, real incompatible environment/global/nesting/light combinations, stale/duplicate/unsupported-boundary/no-permission guards, inactive bindings, default/conflicting wire behavior, atomic refusal and the three new messages in nine locales. All seven cases and the changed existing acceptance remain UNRUN. Source inspection and RAW replay found no actionable blocker; compilation, actual inventories/tests, formatter/lists/localization checks and native mouse/keyboard before-and-after images are still required. + +The next serial development run combines this unit with the reviewed quality-button and minimal TIR test-call changes, uses one normal full-five build with cache retained, then qualifies its own artifacts/inventories. No complete issue row is closed. Default persisted formats, dependencies, command APIs, Nateaux's layout/results/gizmos and physical GPU acceptance are outside this source change. diff --git a/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/assets/locales/pending/cpu-directional-shadow-ui.json b/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/assets/locales/pending/cpu-directional-shadow-ui.json new file mode 100644 index 000000000..49ec6d695 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/assets/locales/pending/cpu-directional-shadow-ui.json @@ -0,0 +1,47 @@ +{ + "en": { + "render.cpu_directional_shadow_help": "CPU optics are temporary and require certified sheets or axis-aligned boxes with opaque body and face appearances. Directional transmitted shadows require global shadows on and all active assignments to agree. Mixed choices, nesting, environment lighting and local lights are unsupported in that mode. This is straight RGB visibility, not refracted shadows or caustics. Subsurface, coats and maps remain unsupported; fixed and progressive sampling retain finite-depth limits.", + "render.cpu_shadow_conflict": "The global directional transmission option conflicts with an optical assignment whose transmitted shadows are off. No authored option was changed.", + "render.cpu_shadow_mixed": "CPU uses one transmitted-shadow switch for all active optical assignments. Mixed on/off choices cannot be represented and have been preserved." + }, + "es": { + "render.cpu_directional_shadow_help": "La óptica CPU es temporal y requiere láminas o cajas alineadas con los ejes certificadas, con aspectos opacos de cuerpo y caras. Las sombras transmitidas direccionales requieren sombras globales activadas y que todas las asignaciones activas coincidan. Ese modo no admite mezclas, nesting, iluminación de entorno ni luces locales. Es visibilidad RGB recta, sin sombras refractadas ni cáusticas. La dispersión subsuperficial, las capas y los mapas siguen sin admitirse; el muestreo fijo y progresivo conserva los límites de profundidad.", + "render.cpu_shadow_conflict": "La opción global de transmisión direccional contradice una asignación óptica con sombras transmitidas desactivadas. No se ha cambiado ninguna opción definida.", + "render.cpu_shadow_mixed": "CPU usa un único control de sombras transmitidas para todas las asignaciones ópticas activas. No puede representar opciones activadas y desactivadas mezcladas; se han conservado." + }, + "de": { + "render.cpu_directional_shadow_help": "CPU-Optik ist temporär und erfordert zertifizierte Scheiben oder achsenparallele Quader mit opaken Körper- und Flächenerscheinungen. Gerichtete durchgelassene Schatten erfordern globale Schatten und übereinstimmende aktive Zuweisungen. Gemischte Optionen, Verschachtelung, Umgebungslicht und lokale Lichter sind in diesem Modus nicht unterstützt. Dies ist geradlinige RGB-Sichtbarkeit, keine gebrochenen Schatten oder Kaustiken. Subsurface-Streuung, Beschichtungen und Maps bleiben nicht unterstützt; feste und progressive Abtastung behalten die endliche Tiefengrenze.", + "render.cpu_shadow_conflict": "Die globale gerichtete Transmission widerspricht einer optischen Zuweisung mit ausgeschalteten durchgelassenen Schatten. Keine festgelegte Option wurde geändert.", + "render.cpu_shadow_mixed": "CPU verwendet einen Schalter für durchgelassene Schatten aller aktiven optischen Zuweisungen. Gemischte Ein-/Aus-Werte sind nicht darstellbar und wurden beibehalten." + }, + "ko": { + "render.cpu_directional_shadow_help": "CPU 광학은 임시 설정이며 불투명한 바디와 면 외관을 가진 인증된 판 또는 축 정렬 상자가 필요합니다. 방향성 투과 그림자는 전역 그림자가 켜져 있고 모든 활성 할당의 설정이 같아야 합니다. 이 모드는 혼합 설정, 중첩, 환경 조명 및 로컬 광원을 지원하지 않습니다. 이는 직선 RGB 가시성이며 굴절 그림자나 코스틱이 아닙니다. 표면하 산란, 코팅 및 맵은 계속 지원하지 않으며 고정 및 점진적 샘플링은 유한 깊이 제한을 유지합니다.", + "render.cpu_shadow_conflict": "전역 방향성 투과 옵션이 투과 그림자가 꺼진 광학 할당과 충돌합니다. 작성된 옵션은 변경되지 않았습니다.", + "render.cpu_shadow_mixed": "CPU는 모든 활성 광학 할당에 하나의 투과 그림자 스위치를 사용합니다. 켜짐과 꺼짐이 섞인 설정은 표현할 수 없으며 그대로 보존되었습니다." + }, + "ar": { + "render.cpu_directional_shadow_help": "بصريات CPU مؤقتة وتتطلب صفائح أو صناديق محاذية للمحاور اجتازت التحقق، بمظاهر معتمة للجسم والأوجه. تتطلب الظلال النافذة الاتجاهية تفعيل الظلال العامة وتطابق كل التعيينات النشطة. لا يدعم هذا الوضع الخيارات المختلطة أو التداخل أو إضاءة البيئة أو الأضواء المحلية. هذه رؤية RGB مستقيمة وليست ظلالًا منكسرة أو كاوستيك. يبقى التشتت تحت السطحي والطلاءات والخرائط غير مدعوم، وتبقى حدود العمق المحدودة لأخذ العينات الثابت والتدريجي.", + "render.cpu_shadow_conflict": "يتعارض خيار النفاذ الاتجاهي العام مع تعيين بصري تكون ظلاله النافذة معطلة. لم يتغير أي خيار محدد.", + "render.cpu_shadow_mixed": "يستخدم CPU مفتاح ظلال نافذة واحدًا لجميع التعيينات البصرية النشطة. لا يمكن تمثيل خليط من التفعيل والتعطيل، وقد تم الاحتفاظ بالخيارات." + }, + "he": { + "render.cpu_directional_shadow_help": "אופטיקת CPU היא זמנית ודורשת יריעות או תיבות מיושרות לצירים שעברו אימות, עם מראה אטום של הגוף והפאות. צללים מועברים כיווניים דורשים צללים כלליים פעילים ואחידות בכל ההקצאות הפעילות. מצב זה אינו תומך בערכים מעורבים, קינון, תאורת סביבה או אורות מקומיים. זו נראות RGB בקו ישר, ללא צללים נשברים או קאוסטיקה. פיזור תת-משטחי, ציפויים ומפות עדיין אינם נתמכים; דגימה קבועה והדרגתית שומרות על מגבלות העומק הסופי.", + "render.cpu_shadow_conflict": "אפשרות ההעברה הכיוונית הכללית סותרת הקצאה אופטית שהצללים המועברים שלה כבויים. שום אפשרות שנקבעה לא שונתה.", + "render.cpu_shadow_mixed": "CPU משתמש במתג צללים מועברים אחד לכל ההקצאות האופטיות הפעילות. לא ניתן לייצג ערכים מעורבים של פעיל וכבוי, והם נשמרו." + }, + "ja": { + "render.cpu_directional_shadow_help": "CPU 光学設定は一時的で、不透明なボディと面の外観を持つ認証済みの薄板または軸に平行なボックスが必要です。平行光源の透過シャドウには全体のシャドウを有効にし、すべての有効な割り当ての設定を一致させる必要があります。このモードでは混在設定、入れ子、環境光、ローカルライトは非対応です。これは直線上の RGB 可視性であり、屈折シャドウやコースティクスではありません。表面下散乱、コート、マップは引き続き非対応で、固定およびプログレッシブサンプリングでも有限深度制限は残ります。", + "render.cpu_shadow_conflict": "全体の平行光透過オプションが、透過シャドウを無効にした光学割り当てと競合しています。設定したオプションは変更されていません。", + "render.cpu_shadow_mixed": "CPU はすべての有効な光学割り当てに単一の透過シャドウスイッチを使用します。有効と無効の混在は表現できないため、その設定を保持しています。" + }, + "vi": { + "render.cpu_directional_shadow_help": "Quang học CPU là tạm thời và cần tấm hoặc hộp song song các trục đã được kiểm chứng, với diện mạo thân và mặt đục. Bóng truyền qua từ đèn định hướng cần bật bóng toàn cục và mọi phép gán đang bật phải cùng lựa chọn. Chế độ này không hỗ trợ lựa chọn lẫn bật/tắt, lồng nhau, ánh sáng môi trường hoặc đèn cục bộ. Đây là độ nhìn thấy RGB theo đường thẳng, không phải bóng khúc xạ hay caustic. Tán xạ dưới bề mặt, lớp phủ và bản đồ vẫn không được hỗ trợ; lấy mẫu cố định và lũy tiến vẫn có giới hạn độ sâu hữu hạn.", + "render.cpu_shadow_conflict": "Tùy chọn truyền sáng định hướng toàn cục xung đột với phép gán quang học có bóng truyền qua đang tắt. Không thay đổi tùy chọn đã soạn nào.", + "render.cpu_shadow_mixed": "CPU dùng một công tắc bóng truyền qua cho tất cả phép gán quang học đang bật. Không thể biểu diễn lựa chọn lẫn bật và tắt; các lựa chọn đã được giữ nguyên." + }, + "zh": { + "render.cpu_directional_shadow_help": "CPU 光学设置是临时的,需要通过认证的薄片或轴对齐盒体,以及不透明的实体和面外观。方向光透射阴影要求开启全局阴影,并且所有启用的分配采用相同设置。此模式不支持混合开关、嵌套、环境照明或局部光源。这是直线 RGB 可见性,并非折射阴影或焦散。次表面散射、涂层和贴图仍不支持;固定和渐进采样仍保留有限深度限制。", + "render.cpu_shadow_conflict": "全局方向光透射选项与关闭透射阴影的光学分配冲突。未更改任何已设置的选项。", + "render.cpu_shadow_mixed": "CPU 对所有启用的光学分配使用一个透射阴影开关。无法表示开启和关闭混合的设置,已保留这些设置。" + } +} diff --git a/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_cpu.rs b/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_cpu.rs new file mode 100644 index 000000000..5d3dd4d0d --- /dev/null +++ b/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_cpu.rs @@ -0,0 +1,856 @@ +//! Transient CPU image controls; engine commands own file capture and admission. +use serde_json::{Value, json}; +use solidcraft_engine::render::job::{CpuBudget, CpuDielectricTransport, RaytraceEnvironmentOptions, ReflectionBody, ReflectionMode}; + +use super::hdr; +use crate::{SolveApp, ui_kit}; + +pub(super) fn validate_progressive_image(app: &SolveApp) -> Result<(), String> { + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + let view = &app.render_workspace.view; + view.raytrace.budget.validate_image(view.draft.width, view.draft.height, view.raytrace.progressive).map_err(|error| error.to_string())?; + } + Ok(()) +} + +pub(super) fn image_limits(app: &SolveApp) -> solidcraft_engine::render::RenderLimits { + if app.render_workspace.view.method == super::ImageMethod::GpuRaytrace { + return solidcraft_engine::render::job::GPU_PATH_LIMITS; + } + if app.render_workspace.view.method != super::ImageMethod::CpuRaytrace { + return Default::default(); + } + let options = &app.render_workspace.view.raytrace; + let mut limits = options.budget.image_limits(options.progressive.is_some()); + if let Some(progressive) = options.progressive { + limits.max_pixels = limits.max_pixels.min(options.budget.limits().max_camera_samples / u64::from(progressive.samples_per_pixel.max(1))); + } + limits +} + +fn budget_key(budget: CpuBudget) -> &'static str { + match budget { + CpuBudget::Compact => "render.children.compact", + CpuBudget::Studio => "render.children.studio", + CpuBudget::Workstation => "render.children.workstation", + } +} + +fn budget_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let budgets = CpuBudget::ALL; + let mut selected = budgets.iter().position(|b| *b == app.render_workspace.view.raytrace.budget).unwrap_or(0); + let labels = budgets.map(|b| app.tr(budget_key(b)).to_string()); + let response = ui.scope(|ui| { + ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { + compact: true, + targets: &["render.cpu_budget_compact", "render.cpu_budget_studio", "render.cpu_budget_workstation"], + ..Default::default() + }, + ) + }); + crate::scenario::publish_rect("render:cpu-budget", response.response.rect); + if response.inner + && let Some(budget) = budgets.get(selected) + { + app.render_workspace.view.raytrace.budget = *budget; + app.render_workspace.view.dirty = true; + } + let limits = app.render_workspace.view.raytrace.budget.limits(); + let note = format!( + "{}: {:.2} GiB · {}: {} · {}: {} · {}: {}. {}", + app.tr("render.cpu_budget_memory"), + limits.max_job_bytes as f64 / 1_073_741_824.0, + app.tr("render.cpu_budget_triangles"), + limits.max_triangles, + app.tr("render.cpu_budget_bodies"), + limits.max_bodies, + app.tr("render.cpu_progressive_spp"), + limits.max_samples_per_pixel, + app.tr("render.cpu_budget_not_guarantee") + ); + ui_kit::text(ui, ¬e, ui_kit::Text::Note("render.cpu_budget_help")); +} +fn set_progressive(app: &mut SolveApp, enabled: bool) { + let options = &mut app.render_workspace.view.raytrace; + if enabled { + options.progressive.get_or_insert_default(); + options.primary_samples = 1; + } else { + options.progressive = None; + } + app.render_workspace.view.dirty = true; +} + +/// The saved CPU choice is independent of sampling, profiles and material bindings. +fn set_dielectric_transport(app: &mut SolveApp, policy: CpuDielectricTransport) -> bool { + let view = &mut app.render_workspace.view; + if view.raytrace.dielectric_transport == policy { + return false; + } + view.raytrace.dielectric_transport = policy; + view.dirty = true; + true +} + +fn dielectric_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let mut selected = usize::from(app.render_workspace.view.raytrace.dielectric_transport == CpuDielectricTransport::StrictTir); + let labels = [app.tr("render.cpu_glass_standard").to_string(), app.tr("render.cpu_glass_continue").to_string()]; + let label = app.tr("render.cpu_glass_label").to_string(); + if ui_kit::row(ui, &label, |ui| { + ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { compact: true, targets: &["render:cpu-glass-standard", "render:cpu-glass-continue"], ..Default::default() }, + ) + }) { + set_dielectric_transport(app, if selected == 1 { CpuDielectricTransport::StrictTir } else { CpuDielectricTransport::LegacyBounded }); + } + ui_kit::text(ui, app.tr("render.cpu_glass_help"), ui_kit::Text::Note("render.cpu_glass_help")); +} + +pub(super) fn progressive_controls(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { + budget_controls(app, ui); + dielectric_controls(app, ui); + let mut selected = usize::from(app.render_workspace.view.raytrace.progressive.is_some()); + let labels = [app.tr("render.children.single_image").to_string(), app.tr("render.cpu_progressive").to_string()]; + let response = ui.scope(|ui| { + ui_kit::row(ui, app.tr("render.children.sampling"), |ui| { + ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { compact: true, targets: &["render:cpu-fixed", "render:cpu-progressive"], ..Default::default() }, + ) + }) + }); + crate::scenario::publish_target("render:cpu-sampling", response.response.rect); + if response.inner { + set_progressive(app, selected == 1); + } + let enabled = app.render_workspace.view.raytrace.progressive.is_some(); + let mut options = app.render_workspace.view.raytrace.progressive.unwrap_or_default(); + if !enabled { + ui_kit::text(ui, app.tr("render.children.progressive_reason"), ui_kit::Text::Note("render.children.progressive_reason")); + } + ui.add_enabled_ui(enabled, |ui| { + let response = + ui_kit::row(ui, app.tr("render.cpu_progressive_spp"), |ui| ui_kit::number_field(ui, &mut options.samples_per_pixel, 1..=4096, 1.0, "")); + app.render_workspace.view.dirty |= response.changed(); + crate::scenario::publish_target("render:cpu-spp", response.rect); + let response = + ui_kit::row(ui, app.tr("render.cpu_progressive_seed"), |ui| ui_kit::number_field(ui, &mut options.seed, 0..=u32::MAX, 1.0, "")); + app.render_workspace.view.dirty |= response.changed(); + crate::scenario::publish_target("render:cpu-seed", response.rect); + }); + if enabled { + app.render_workspace.view.raytrace.progressive = Some(options); + } + ui_kit::text(ui, app.tr("render.cpu_progressive_help"), ui_kit::Text::Note("render.cpu_progressive_help")); + enabled +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Environment { + #[default] + None, + Constant, + Hdr, +} + +#[derive(Clone, Debug)] +pub(super) struct View { + #[cfg(test)] + pub selected_body: Option, + #[cfg(test)] + pub body_filter: String, + pub environment: Environment, + pub hdr: hdr::Input, + pub rotation_rad: f64, + pub intensity: f64, + pub samples: u32, + pub color: [f64; 3], + pub checked: Option, + /// Request-local, explicitly selected certified-box nesting; never inferred from GPU state. + pub nested_media: bool, + bindings: std::collections::BTreeMap, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct Target { + ordinal: usize, + feature: u64, + component: u64, +} + +#[derive(Clone, Debug)] +struct Binding { + target: Target, + revision: u64, + document: std::sync::Weak, + // Interactive may follow appearance/render-only edits only while this exact + // evaluated world survives in the same open document. Weak ownership avoids + // retaining old geometry and prevents pointer reuse after the world drops. + session_uid: u64, + world: std::sync::Weak, +} + +#[derive(Clone, Debug)] +pub(super) struct Checked { + pub request: Value, + pub revision: u64, + pub environment: Value, + document: std::sync::Weak, +} + +impl Default for View { + fn default() -> Self { + Self { + #[cfg(test)] + selected_body: None, + #[cfg(test)] + body_filter: String::new(), + environment: Environment::None, + hdr: hdr::Input::default(), + rotation_rad: 0.0, + intensity: 1.0, + samples: 16, + color: [1.0; 3], + checked: None, + nested_media: false, + bindings: Default::default(), + } + } +} + +fn valid_name(name: &str) -> bool { + !name.is_empty() && name.len() <= 128 && !name.chars().any(char::is_control) +} + +fn target(app: &SolveApp, name: &str) -> Option { + if !valid_name(name) || app.session.model.is_stale() { + return None; + } + let world = app.session.world_state(); + let mut matches = world.bodies.iter().filter(|body| app.session.body_visible(&body.name)).enumerate().filter(|(_, body)| body.name == name); + let (ordinal, body) = matches.next()?; + if matches.next().is_some() { + return None; + } + Some(Target { ordinal, feature: body.feature, component: body.component }) +} + +fn unique_visible_body(app: &SolveApp, name: &str) -> bool { + target(app, name).is_some() +} + +fn binding_current(app: &SolveApp, name: &str) -> bool { + app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| { + binding.revision == app.session.revision + && std::sync::Weak::ptr_eq(&binding.document, &std::sync::Arc::downgrade(&app.session.doc)) + && target(app, name).as_ref() == Some(&binding.target) + }) +} + +// Unlike final Check/Start, Interactive may refresh harmless appearance/render +// edits. The engine retains the exact world Arc for those edits (refresh_render). +// No geometry extraction, cold meshing, name-only rebinding or revision stamping. +fn binding_interactive_world_current(app: &SolveApp, name: &str) -> bool { + app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| { + binding.session_uid == app.session.uid + && !app.session.model.is_stale() + && app + .session + .interactive_cached_world_state() + .is_some_and(|world| std::sync::Weak::ptr_eq(&binding.world, &std::sync::Arc::downgrade(&world))) + }) +} + +fn binding_interactive_current(app: &SolveApp, name: &str) -> bool { + binding_interactive_world_current(app, name) + && app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| target(app, name).as_ref() == Some(&binding.target)) +} + +pub(super) fn revalidate(app: &mut SolveApp, name: &str) -> Result<(), String> { + let current = target(app, name).ok_or_else(|| app.tr("render.cpu_body_missing").to_string())?; + if app.render_workspace.view.cpu.bindings.get(name).is_none_or(|binding| binding.target != current) { + return Err(app.tr("render.cpu_body_missing").to_string()); + } + let revision = app.session.revision; + let document = std::sync::Arc::downgrade(&app.session.doc); + let world = std::sync::Arc::downgrade(&app.session.world_state()); + let session_uid = app.session.uid; + if let Some(binding) = app.render_workspace.view.cpu.bindings.get_mut(name) { + binding.revision = revision; + binding.document = document; + binding.session_uid = session_uid; + binding.world = world; + } + Ok(()) +} + +/// A removed, hidden or ambiguous body never silently becomes a different target. +pub(super) fn set_reflection(app: &mut SolveApp, name: &str, mode: Option) -> Result<(), String> { + let selected = if mode.is_some() { Some(target(app, name).ok_or_else(|| app.tr("render.cpu_body_missing").to_string())?) } else { None }; + // Changing the mode of an existing row is not a new body selection. Only an + // explicit confirmation of the same target, or Off followed by Add, may + // establish a fresh binding after the document or body identity changes. + if mode.is_some() + && app.render_workspace.view.raytrace.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| entry.body == name)) + && !binding_current(app, name) + { + return Err(app.tr("render.cpu_binding_stale").to_string()); + } + let message = app.tr("render.cpu_reflection_limit").to_string(); + let options = &mut app.render_workspace.view.raytrace; + if let Some(mode) = mode { + let mut reflections = options.reflections.clone().unwrap_or_default(); + if let Some(entry) = reflections.bodies.iter_mut().find(|entry| entry.body == name) { + entry.mode = mode; + } else { + if reflections.bodies.len() >= 64 { + return Err(message); + } + reflections.bodies.try_reserve_exact(1).map_err(|_| message.clone())?; + if reflections.bodies.capacity() > 64 { + return Err(message); + } + reflections.bodies.push(ReflectionBody { body: name.to_string(), mode }); + } + options.reflections = Some(reflections); + } else if let Some(reflections) = &mut options.reflections { + reflections.bodies.retain(|entry| entry.body != name); + if reflections.bodies.is_empty() { + options.reflections = None; + } + } + if let Some(target) = selected { + app.render_workspace.view.cpu.bindings.insert( + name.to_string(), + Binding { + target, + revision: app.session.revision, + document: std::sync::Arc::downgrade(&app.session.doc), + session_uid: app.session.uid, + world: std::sync::Arc::downgrade(&app.session.world_state()), + }, + ); + } else { + app.render_workspace.view.cpu.bindings.remove(name); + } + Ok(()) +} + +/// Shared by the parent Check and Start builder. This does not read an HDR file. +pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { + params_with_binding_policy(app, params, binding_current) +} + +/// Interactive-only wire lowering. This does not requalify final Check/Start, +/// change a stored binding or read an HDR file; the engine still captures and admits it. +pub(super) fn params_interactive(app: &SolveApp, params: &mut Value) -> Result<(), String> { + // runtime_image_request composes the explicit material DTO immediately + // after these numerical controls, exactly once. The engine then converts + // the separate Interactive request to progressive sampling and admits its + // complete optics; a Fixed editor never licenses dropping that intent. + // Refuse unproved bound worlds before shared lowering checks visibility via + // target()/world_state(). Empty reflections never require a warm world. + if app + .render_workspace + .view + .raytrace + .reflections + .as_ref() + .is_some_and(|r| r.bodies.iter().any(|entry| !binding_interactive_world_current(app, &entry.body))) + { + return Err(app.tr("render.cpu_binding_stale").to_string()); + } + params_with_binding_policy(app, params, binding_interactive_current) +} + +fn params_with_binding_policy(app: &SolveApp, params: &mut Value, current: fn(&SolveApp, &str) -> bool) -> Result<(), String> { + let base = &app.render_workspace.view.raytrace; + if base.anisotropic_faces.iter().any(Option::is_some) + || !base.dielectrics.is_empty() + || base.environment.is_some() + || base.surface_effects.is_some() + || base.emissions.is_some() + { + return Err(app.tr("render.cpu_options_pending").to_string()); + } + if base.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| !unique_visible_body(app, &entry.body))) { + return Err(app.tr("render.cpu_body_missing").to_string()); + } + if base.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| !current(app, &entry.body))) { + return Err(app.tr("render.cpu_binding_stale").to_string()); + } + let view = &app.render_workspace.view.cpu; + let mut options = base.clone(); + if options.area_samples.is_some_and(|n| !matches!(n, 1 | 4 | 16 | 64)) { + return Err(crate::i18n::tr("render.error_area_samples").into()); + } + if options.area_lights.as_ref().is_none_or(Vec::is_empty) { + options.area_samples = None; + options.seed = None; + } + options.exposure_ev = app.render_workspace.view.draft.exposure_ev; + // Runtime CPU requests keep the same single saved EV authority as typed jobs. + params["settings"]["exposure_ev"] = json!(0.0); + if view.environment != Environment::None { + if !view.intensity.is_finite() || !(0.0..=64.0).contains(&view.intensity) { + return Err(app.tr("render.cpu_environment_bounds").to_string()); + } + match view.environment { + Environment::Constant => options.environment = Some(RaytraceEnvironmentOptions { color: view.color, intensity: view.intensity }), + Environment::Hdr => { + if !view.rotation_rad.is_finite() || view.rotation_rad.abs() > 1e6 || !matches!(view.samples, 1 | 4 | 16 | 64) { + return Err(app.tr("render.cpu_environment_bounds").to_string()); + } + let mut environment = hdr::request(app, hdr::Target::Cpu)?; + environment["rotation_radians"] = json!(view.rotation_rad); + environment["intensity"] = json!(view.intensity); + environment["samples"] = json!(view.samples); + params["environment"] = environment; + } + Environment::None => {} + } + } + options.validate().map_err(|error| error.to_string())?; + params["integrator"] = json!("raytrace"); + params["raytrace"] = json!(options); + Ok(()) +} + +#[cfg(test)] +pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { + for (id, key, section) in [ + ("render_cpu_reflections", "render.cpu_reflections", 0), + ("render_cpu_environment", "render.cpu_environment", 1), + ("render_cpu_lights", "render.cpu_lights", 2), + ] { + let title = app.tr(key).to_string(); + ui_kit::section(ui, id, &title, false, |ui| match section { + 0 => reflection_controls(app, ui), + 1 => environment_controls(app, ui), + _ => light_controls(app, ui), + }); + } + ui.small(app.tr("render.cpu_runtime_help")); +} + +#[cfg(test)] +pub(super) fn reflection_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + ui.small(app.tr("render.cpu_reflection_help")); + let entries = app.render_workspace.view.raytrace.reflections.as_ref().map(|r| r.bodies.clone()).unwrap_or_default(); + for entry in entries { + ui.label(&entry.body); + if !binding_current(app, &entry.body) { + ui.small(app.tr("render.cpu_binding_stale")); + if ui_kit::button(ui, app.tr("render.cpu_binding_confirm"), ui_kit::Button::Normal).clicked() + && let Err(error) = revalidate(app, &entry.body) + { + app.set_status(error, true); + } + } + let selected = match entry.mode { + ReflectionMode::Mirror => "render.cpu_reflection_mirror", + ReflectionMode::RoughSpecular => "render.cpu_reflection_rough", + }; + let label = app.tr(selected).to_string(); + let mode_control = ui_kit::dropdown_menu(ui, ("cpu_reflection_mode", &entry.body), &label, |ui| { + for (mode, key) in [ + (None, "render.cpu_reflection_off"), + (Some(ReflectionMode::Mirror), "render.cpu_reflection_mirror"), + (Some(ReflectionMode::RoughSpecular), "render.cpu_reflection_rough"), + ] { + let enabled = mode.is_none() || binding_current(app, &entry.body); + if ui.add_enabled_ui(enabled, |ui| ui_kit::list_picker(ui, key, app.tr(key), mode == Some(entry.mode))).inner.clicked() { + if let Err(error) = set_reflection(app, &entry.body, mode) { + app.set_status(error, true); + } + ui.close(); + } + } + }); + crate::scenario::publish_handle(&format!("render:cpu-reflection-mode:{}", entry.body), mode_control.rect.center()); + } + let hint = app.tr("render.cpu_body_filter").to_string(); + ui_kit::bounded_cell_editor(ui, ui.id().with("cpu_body_filter"), &mut app.render_workspace.view.cpu.body_filter, &hint, false, 128); + let selected = app.render_workspace.view.cpu.selected_body.clone(); + let label = selected.clone().unwrap_or_else(|| app.tr("render.cpu_body_choose").to_string()); + let world = app.session.world_state(); + let filter = app.render_workspace.view.cpu.body_filter.to_lowercase(); + let candidates: Vec<_> = world + .bodies + .iter() + .filter(|body| app.session.body_visible(&body.name) && body.name.to_lowercase().contains(&filter)) + .take(257) + .map(|body| body.name.as_str()) + .collect(); + let dropdown = ui_kit::dropdown_menu(ui, "cpu_reflection_body", &label, |ui| { + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + for (shown, name) in candidates.iter().enumerate() { + if shown == 256 { + ui.small(app.tr("render.cpu_body_filter_more")); + break; + } + let response = + ui.add_enabled_ui(valid_name(name), |ui| ui_kit::list_picker(ui, name, name, selected.as_deref() == Some(*name))).inner; + if response.clicked() { + app.render_workspace.view.cpu.selected_body = Some((*name).to_string()); + ui.close(); + } + } + }); + }); + crate::scenario::publish_handle("render:cpu-reflection-body", dropdown.rect.center()); + let can_add = selected.as_ref().is_some_and(|name| unique_visible_body(app, name)) + && app.render_workspace.view.raytrace.reflections.as_ref().is_none_or(|r| r.bodies.len() < 64); + let add = ui_kit::button(ui, app.tr("render.cpu_reflection_add"), ui_kit::Button::Enabled(can_add)); + crate::scenario::publish_handle("render:cpu-reflection-add", add.rect.center()); + if add.clicked() + && let Some(name) = selected + && let Err(error) = set_reflection(app, &name, Some(ReflectionMode::RoughSpecular)) + { + app.set_status(error, true); + } + reflection_sampling_controls(app, ui); +} + +/// Existing global reflection budget, shared during the Sampling-editor migration. +pub(super) fn reflection_sampling_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let depth = app.tr("render.cpu_reflection_depth").to_string(); + let samples = app.tr("render.cpu_reflection_samples").to_string(); + if let Some(reflections) = &mut app.render_workspace.view.raytrace.reflections { + ui_kit::row(ui, &depth, |ui| ui_kit::number_field(ui, &mut reflections.max_bounces, 1..=8, 1.0, "")); + ui_kit::row(ui, &samples, |ui| ui_kit::number_field(ui, &mut reflections.samples, 1..=64, 1.0, "")); + } else { + ui.small(app.tr("render.cpu_reflection_empty")); + } +} + +#[cfg(test)] +pub(super) fn environment_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let selected = app.render_workspace.view.cpu.environment; + let key = match selected { + Environment::None => "render.cpu_environment_none", + Environment::Constant => "render.cpu_environment_constant", + Environment::Hdr => "render.studio_hdr", + }; + let label = app.tr(key).to_string(); + ui_kit::dropdown_menu(ui, "cpu_environment_kind", &label, |ui| { + for (value, key) in [ + (Environment::None, "render.cpu_environment_none"), + (Environment::Constant, "render.cpu_environment_constant"), + (Environment::Hdr, "render.studio_hdr"), + ] { + if ui_kit::list_picker(ui, key, app.tr(key), value == selected).clicked() { + app.render_workspace.view.cpu.environment = value; + ui.close(); + } + } + }); + if app.render_workspace.view.cpu.environment == Environment::None { + return; + } + if app.render_workspace.view.cpu.environment == Environment::Constant { + let color = app.tr("render.cpu_linear_color").to_string(); + vector(ui, &color, &mut app.render_workspace.view.cpu.color, 0.0..=1.0, 0.01, ""); + ui.small(app.tr("render.cpu_constant_help")); + } else { + hdr::controls(app, ui, hdr::Target::Cpu); + ui.small(app.tr("render.cpu_hdr_help")); + ui.label(app.tr("render.studio_rotation")); + let mut degrees = app.render_workspace.view.cpu.rotation_rad.to_degrees(); + if ui_kit::number_field(ui, &mut degrees, -1e6_f64.to_degrees()..=1e6_f64.to_degrees(), 1.0, "°").changed() { + app.render_workspace.view.cpu.rotation_rad = degrees.to_radians(); + } + ui.label(app.tr("render.cpu_environment_samples")); + let samples = app.render_workspace.view.cpu.samples; + ui_kit::dropdown_menu(ui, "cpu_hdr_samples", &samples.to_string(), |ui| { + for value in [1, 4, 16, 64] { + if ui_kit::list_picker(ui, &value.to_string(), &value.to_string(), value == samples).clicked() { + app.render_workspace.view.cpu.samples = value; + ui.close(); + } + } + }); + ui.small(app.tr("render.cpu_hdr_reflection_help")); + } + ui.label(app.tr("render.studio_intensity")); + ui_kit::number_field(ui, &mut app.render_workspace.view.cpu.intensity, 0.0..=64.0, 0.1, ""); + ui.small(app.tr("render.cpu_environment_background")); +} + +#[cfg(test)] +fn vector(ui: &mut egui::Ui, label: &str, value: &mut [f64; 3], range: std::ops::RangeInclusive, speed: f64, suffix: &str) { + ui.label(label); + ui.horizontal(|ui| { + for component in value { + ui_kit::number_field(ui, component, range.clone(), speed, suffix); + } + }); +} + +#[cfg(test)] +pub(super) fn light_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + super::light::lighting(app, ui); +} + +pub(super) fn record_checked(app: &mut SolveApp, params: &Value, reply: &Value) { + if params["integrator"] == "raytrace" || params["settings"]["job"]["method"] == "cpu_raytrace" { + app.render_workspace.view.cpu.checked = Some(Checked { + request: params.clone(), + revision: app.session.revision, + environment: reply["environment"].clone(), + document: std::sync::Arc::downgrade(&app.session.doc), + }); + } +} + +fn metadata(app: &SolveApp, ui: &mut egui::Ui, info: &Value) { + let Some(hash) = info["source_sha256"].as_array().filter(|hash| hash.len() == 32) else { return }; + let digest: Option> = hash.iter().map(|byte| byte.as_u64().and_then(|n| u8::try_from(n).ok())).collect(); + let Some(digest) = digest else { return }; + let digest: String = digest.into_iter().map(|byte| format!("{byte:02x}")).collect(); + let width = info["header"]["width"].as_u64().unwrap_or(0); + let height = info["header"]["height"].as_u64().unwrap_or(0); + ui.label(format!("{width} × {height} px")); + ui.label(format!("{}: {}", app.tr("render.cpu_environment_samples"), info["samples"].as_u64().unwrap_or(0))); + ui.label(format!("{}: {:.2}", app.tr("render.studio_intensity"), info["intensity"].as_f64().unwrap_or(0.0))); + ui.label(format!("{}: {:.1}°", app.tr("render.studio_rotation"), info["rotation_radians"].as_f64().unwrap_or(0.0).to_degrees())); + ui.label(format!("SHA-256: {digest}")); +} + +pub(super) fn checked_status(app: &SolveApp, ui: &mut egui::Ui, params: Option<&Value>) { + if app.render_workspace.view.method != super::ImageMethod::CpuRaytrace { + return; + } + if let Some(checked) = &app.render_workspace.view.cpu.checked { + let title = app.tr("render.cpu_last_check").to_string(); + ui_kit::section(ui, "cpu_last_check", &title, false, |ui| { + if params != Some(&checked.request) + || checked.revision != app.session.revision + || !std::sync::Weak::ptr_eq(&checked.document, &std::sync::Arc::downgrade(&app.session.doc)) + { + ui.small(app.tr("render.cpu_check_changed")); + } + metadata(app, ui, &checked.environment); + ui.small(app.tr("render.cpu_check_capture_help")); + }); + } +} + +pub(super) fn captured_status(app: &SolveApp, ui: &mut egui::Ui, status: &Value) { + if status["request"]["integrator"] == "raytrace" && status["environment"]["source_sha256"].is_array() { + let title = app.tr("render.cpu_captured_hdr").to_string(); + ui_kit::section(ui, "cpu_captured_hdr", &title, false, |ui| metadata(app, ui, &status["environment"])); + } +} + +#[cfg(test)] +fn dielectric_policy_harness() -> crate::scenario::Harness { + let mut h = crate::scenario::Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = super::ImageMethod::CpuRaytrace; + h.app.render_workspace.view.result = false; + h.app.render_workspace.view.name = "Policy".into(); + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.exposure_ev = 0.0; + h.app.render_workspace.view.raytrace = Default::default(); + h.app.render_workspace.view.cpu = View::default(); + h +} + +#[cfg(test)] +#[test] +fn cpu_glass_policy_no_binding_ui_snapshot_save_reopen_load_preserves_portable_choice() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = dielectric_policy_harness(); + assert!(!set_dielectric_transport(&mut h.app, CpuDielectricTransport::LegacyBounded)); + assert!(set_dielectric_transport(&mut h.app, CpuDielectricTransport::StrictTir)); + assert!(h.app.render_workspace.view.dirty); + assert!(!super::setups::has_runtime_inputs(&h.app), "the choice itself is portable"); + let saved = super::setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::CpuRaytrace { options }) = &saved.job else { panic!("CPU draft changed method") }; + assert_eq!(options.dielectric_transport, CpuDielectricTransport::StrictTir); + let wire = super::image_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["job"]["options"]["dielectric_transport"], "strict_tir"); + super::setups::save(&mut h.app).unwrap(); + let document = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = solidcraft_engine::Session::new(document); + h.app.render_workspace.view.raytrace.dielectric_transport = CpuDielectricTransport::LegacyBounded; + super::setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.raytrace.dielectric_transport, CpuDielectricTransport::StrictTir); + assert_eq!(super::setups::snapshot(&h.app).unwrap(), saved); + assert_eq!(super::image_request(&h.app).unwrap()["settings"]["job"]["options"]["dielectric_transport"], "strict_tir"); + assert!(set_dielectric_transport(&mut h.app, CpuDielectricTransport::LegacyBounded)); + assert!(serde_json::to_value(super::setups::snapshot(&h.app).unwrap()).unwrap()["job"]["options"].get("dielectric_transport").is_none()); +} + +#[cfg(test)] +#[test] +fn cpu_glass_policy_numeric_lowering_and_active_light_filter_preserve_the_exact_choice() { + use solidcraft_engine::render::job::DirectionalLightOptions; + let mut h = dielectric_policy_harness(); + h.app.render_workspace.view.raytrace.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + h.app.render_workspace.view.lights.visibility.muted.insert("directional:0".into()); + for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { + set_dielectric_transport(&mut h.app, policy); + let source = h.app.render_workspace.view.raytrace.clone(); + for interactive in [false, true] { + let mut wire = json!({"settings":{"job":null}}); + if interactive { + params_interactive(&h.app, &mut wire).unwrap(); + } else { + params(&h.app, &mut wire).unwrap(); + } + super::materials::params(&h.app, &mut wire).unwrap(); + let wire = super::light::filter_request(&h.app, wire).unwrap(); + let options: solidcraft_engine::render::job::RaytraceOptions = serde_json::from_value(wire["raytrace"].clone()).unwrap(); + assert_eq!(options.dielectric_transport, policy); + assert_eq!(options.lights.as_ref().unwrap()[0].intensity, 0.0); + assert_eq!(h.app.render_workspace.view.raytrace, source, "transient visibility must not rewrite authored input"); + } + let portable = super::image_request(&h.app).unwrap(); + let options: solidcraft_engine::doc::render_settings::CpuJob = + serde_json::from_value(portable["settings"]["job"]["options"].clone()).unwrap(); + assert_eq!(options.dielectric_transport, policy); + } +} + +#[cfg(test)] +#[test] +fn cpu_glass_policy_selection_preserves_unsupported_opaque_reflection_and_advanced_intent() { + use solidcraft_engine::render::job::{EmissionSides, SurfaceEmission}; + let mut h = dielectric_policy_harness(); + h.app.session.execute("solid.box", &json!({"length":20,"width":20,"height":10})).unwrap(); + h.app.session.execute("render.scene", &json!({})).unwrap(); + let target = super::materials::read_targets(&mut h.app).unwrap().remove(0); + set_reflection(&mut h.app, &target.name, Some(ReflectionMode::Mirror)).unwrap(); + let authored = h.app.render_workspace.view.raytrace.clone(); + set_dielectric_transport(&mut h.app, CpuDielectricTransport::StrictTir); + assert_eq!(h.app.render_workspace.view.raytrace.reflections, authored.reflections); + assert!(super::image_request(&h.app).is_err()); + assert!(super::interactive_request(&h.app).is_err()); + assert_eq!(h.app.render_workspace.view.raytrace.reflections, authored.reflections); + assert_eq!(h.app.render_workspace.view.raytrace.dielectric_transport, CpuDielectricTransport::StrictTir); + h.app.render_workspace.view.raytrace.reflections = None; + h.app.render_workspace.view.raytrace.emissions = Some(vec![SurfaceEmission { + body_index: target.ordinal, + body: target.name, + color: [1.0, 0.5, 0.25], + strength: 1.0, + sides: EmissionSides::Front, + }]); + let authored = h.app.render_workspace.view.raytrace.clone(); + assert!(super::image_request(&h.app).is_err()); + assert!(super::interactive_request(&h.app).is_err()); + assert_eq!(h.app.render_workspace.view.raytrace, authored); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[test] +fn native_cpu_glass_policy_public_ui_check_start_and_interactive_preserve_real_material_and_visibility() { + use solidcraft_engine::render::job::interactive::VisualRevision; + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions, DirectionalLightOptions, HostKind, Integrator, JobId, Phase}; + use solidcraft_engine::schema::render_ui::Action; + use std::time::Duration; + let host = CpuHost::for_platform().unwrap(); + assert_eq!(host.kind(), HostKind::NativeWorker); + host.validate_integrator(Integrator::Raytrace).unwrap(); + eprintln!("CPU_GLASS_POLICY_UI_BRANCH cpu_supported=true"); + for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { + let mut h = dielectric_policy_harness(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.session.execute("solid.box", &json!({"length":20,"width":20,"height":10})).unwrap(); + h.app.session.execute("render.scene", &json!({})).unwrap(); + set_dielectric_transport(&mut h.app, policy); + h.app.render_workspace.view.raytrace.lights = + Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + h.app.render_workspace.view.lights.visibility.muted.insert("directional:0".into()); + let target = super::materials::read_targets(&mut h.app).unwrap().remove(0); + let mut binding = super::materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.cpu_optics = true; + // Explicit index-matched certified box: this is capture/consumer + // acceptance, not a new oracle for general reflective glass quality. + binding.glass.ior = 1.0; + binding.glass.boundary = super::materials::Boundary::Box; + binding.glass.thickness = 0.0; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + assert!(super::setups::snapshot(&h.app).is_err(), "captured body bindings remain runtime-only"); + for progressive in [false, true] { + h.app.render_workspace.view.raytrace.progressive = progressive.then_some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 411 }); + let wire = super::image_request(&h.app).unwrap(); + assert_eq!(wire["raytrace"]["dielectrics"].as_array().unwrap().len(), 1); + let checked = h.app.session.execute("render.preflight", &wire).unwrap(); + record_checked(&mut h.app, &wire, &checked); + let revision = h.app.session.revision; + let other = + if policy == CpuDielectricTransport::StrictTir { CpuDielectricTransport::LegacyBounded } else { CpuDielectricTransport::StrictTir }; + set_dielectric_transport(&mut h.app, other); + assert_ne!(Some(&super::image_request(&h.app).unwrap()), h.app.render_workspace.view.cpu.checked.as_ref().map(|c| &c.request)); + assert_eq!(h.app.session.revision, revision); + set_dielectric_transport(&mut h.app, policy); + let started = h.app.session.execute("render.start", &wire).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let final_handle = h.app.session.render_job_handle(id).unwrap(); + let final_status = final_handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(final_status.progress.phase, Phase::Completed, "{:?}", final_status.error); + assert_eq!(json!(final_status.request), checked["request"]); + assert_eq!(final_status.request.raytrace.as_ref().unwrap().dielectric_transport, policy); + assert!(final_handle.frame().unwrap().is_some()); + let preview_wire = super::interactive_request(&h.app).unwrap(); + let context = h.app.session.interactive_render().unwrap(); + context.enable(VisualRevision { scene_generation: revision, visual_revision: 1 }, Duration::ZERO).unwrap(); + let ticket = context.capture(Duration::from_millis(201)).unwrap().unwrap(); + assert!(context.snapshot(&h.app.session, ticket, &preview_wire).unwrap().run().unwrap()); + let preview_handle = context.current().unwrap().unwrap(); + let status = preview_handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let captured = status.request.raytrace.as_ref().unwrap(); + assert_eq!(captured.dielectric_transport, policy); + assert_eq!(captured.dielectrics, final_status.request.raytrace.as_ref().unwrap().dielectrics); + assert_eq!(captured.lights.as_ref().unwrap()[0].intensity, 0.0); + assert_ne!(status.job, final_status.job); + assert!(final_handle.frame().unwrap().is_some(), "Interactive cannot replace the final source"); + context.disable().unwrap(); + } + // Exercise actual UI intent observation while paused, without a fake + // receiver or a second capture worker. No timer result is asserted. + super::interactive::apply_command(&mut h.app, Action::On).unwrap(); + let before = super::interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + super::interactive::apply_command(&mut h.app, Action::Pause).unwrap(); + let revision = h.app.session.revision; + set_dielectric_transport( + &mut h.app, + if policy == CpuDielectricTransport::StrictTir { CpuDielectricTransport::LegacyBounded } else { CpuDielectricTransport::StrictTir }, + ); + super::interactive::apply_command(&mut h.app, Action::Resume).unwrap(); + assert!(super::interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > before); + assert_eq!(h.app.session.revision, revision); + super::interactive::apply_command(&mut h.app, Action::Off).unwrap(); + h.app.render_workspace.view.materials.bindings[0].glass.shadows = true; + let shadow_wire = super::image_request(&h.app).unwrap(); + let shadow_options: solidcraft_engine::render::job::RaytraceOptions = serde_json::from_value(shadow_wire["raytrace"].clone()).unwrap(); + assert!(shadow_options.directional_shadow_transmission); + assert!(shadow_options.shadows); + assert_eq!(shadow_options.dielectric_transport, h.app.render_workspace.view.raytrace.dielectric_transport); + assert_eq!(shadow_options.dielectrics[0].ior, 1.0); + let shadow_check = h.app.session.execute("render.preflight", &shadow_wire).unwrap(); + let shadow_request: solidcraft_engine::render::job::ImageRequest = serde_json::from_value(shadow_check["request"].clone()).unwrap(); + assert_eq!(shadow_request.raytrace.as_ref(), Some(&shadow_options)); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission, "the bridge is request-local"); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + h.app.render_workspace.view.materials.bindings[0].glass.shadows = false; + h.app.render_workspace.view.materials.bindings[0].maps_enabled = true; + assert!(super::interactive_request(&h.app).is_err()); + assert!(h.app.render_workspace.view.materials.bindings[0].maps_enabled); + } +} diff --git a/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_materials.rs b/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_materials.rs new file mode 100644 index 000000000..516b8b74c --- /dev/null +++ b/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_materials.rs @@ -0,0 +1,1196 @@ +//! Transient body-level optical overrides for explicitly selected image transports. +//! The model's appearances, physical material cards and saved setups are not changed. +use std::sync::{Arc, Weak}; + +use serde::Deserialize; +use serde_json::{Value, json}; +use solidcraft_engine::{ + doc::{ + Document, + appearance_pack::{self, GlassBoundary, Recipe}, + }, + geom::Vec3, + render::{ + clear_coat::ClearCoat, + job::textures::{BaseColorMode, PlanarFrame}, + surface::OpaqueSurface, + transmission::Transmission, + }, +}; + +use crate::{SolveApp, theme::Tokens, ui_kit}; + +const MAX_BINDINGS: usize = 128; + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +pub(super) struct Target { + #[serde(default)] + pub stable_target: Option, + pub ordinal: usize, + pub name: String, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Boundary { + Thin, + Box, + #[default] + Closed, +} +impl Boundary { + fn wire(self) -> &'static str { + match self { + Self::Thin => "thin_sheet", + Self::Box => "closed_box", + Self::Closed => "closed_mesh", + } + } +} + +#[derive(Clone, Debug)] +pub(super) struct Glass { + pub recipe: Option<&'static str>, + pub ior: f64, + pub absorption: [f64; 3], + pub boundary: Boundary, + pub thickness: f64, + pub shadows: bool, + pub subsurface: Option, +} +impl Default for Glass { + fn default() -> Self { + Self { recipe: None, ior: 1.5, absorption: [0.0; 3], boundary: Boundary::Closed, thickness: 1.0, shadows: false, subsurface: None } + } +} +impl Glass { + pub(super) fn recipe(id: &str) -> Result { + let preset = appearance_pack::find(id).ok_or_else(|| crate::i18n::tr("render.error_glass_recipe").to_string())?; + let Recipe::Glass(recipe) = preset.recipe else { return Err(crate::i18n::tr("render.error_physical_glass").into()) }; + recipe.validate().map_err(|e| e.to_string())?; + let (boundary, thickness) = match recipe.boundary { + GlassBoundary::Thin { thickness_mm } => (Boundary::Thin, thickness_mm), + GlassBoundary::Closed => (Boundary::Closed, 1.0), + }; + Ok(Self { + subsurface: None, + recipe: Some(preset.id), + ior: recipe.dielectric_ior, + absorption: recipe.transmission_linear_rgb.map(|t| -t.ln() / recipe.reference_path_mm), + boundary, + thickness, + shadows: boundary == Boundary::Thin, + }) + } +} + +#[derive(Clone, Debug)] +pub(super) struct Coat { + pub weight: f64, + pub roughness: f64, + pub ior: f64, +} +impl Default for Coat { + fn default() -> Self { + Self { weight: 1.0, roughness: 0.12, ior: 1.5 } + } +} + +#[derive(Clone, Debug)] +pub(super) struct Maps { + pub color: String, + pub normal: String, + pub roughness: String, + pub metallic: String, + pub base_color_mode: BaseColorMode, + pub flip_v: bool, + pub strength: f64, + pub frame: PlanarFrame, +} +impl Default for Maps { + fn default() -> Self { + Self { + color: String::new(), + normal: String::new(), + roughness: String::new(), + metallic: String::new(), + base_color_mode: BaseColorMode::Modulate, + flip_v: false, + strength: 1.0, + frame: PlanarFrame { origin: [0.0; 3], u: [10.0, 0.0, 0.0], v: [0.0, 10.0, 0.0] }, + } + } +} + +#[derive(Clone, Debug)] +pub(super) struct Binding { + pub target: Target, + revision: u64, + document: Weak, + pub enabled: bool, + pub glass_enabled: bool, + pub glass: Glass, + /// Explicit request-local CPU authorisation; old GPU bindings keep their refusal. + pub cpu_optics: bool, + pub coat_enabled: bool, + pub coat: Coat, + pub maps_enabled: bool, + pub maps: Maps, + replace_saved_optics: bool, +} +impl Binding { + pub(super) fn new(target: Target, app: &SolveApp) -> Self { + Self { + target, + revision: app.session.revision, + document: Arc::downgrade(&app.session.doc), + enabled: true, + glass_enabled: false, + glass: Glass::default(), + cpu_optics: false, + coat_enabled: false, + coat: Coat::default(), + maps_enabled: false, + maps: Maps::default(), + replace_saved_optics: false, + } + } + fn current(&self, app: &SolveApp) -> bool { + self.revision == app.session.revision && Weak::ptr_eq(&self.document, &Arc::downgrade(&app.session.doc)) && !app.session.model.is_stale() + } + fn active(&self) -> bool { + self.enabled && (self.glass_enabled || self.coat_enabled || self.maps_enabled) + } +} + +#[derive(Clone, Debug, Default)] +pub(super) struct View { + pub enabled: bool, + pub bindings: Vec, + targets: Vec, + target: Option, + target_search: String, + selected: Option, + target_revision: Option, + target_document: Option>, + pending_remove: Option, +} + +#[derive(Clone, Debug)] +struct PendingRemoval { + name: String, + target: solidcraft_engine::doc::render_surface::RenderBodyTarget, + revision: u64, + document: Weak, +} + +pub(super) fn read_targets(app: &mut SolveApp) -> Result, String> { + let reply = app.run("render.scene", json!({}))?; + let values = reply.get("bodies").and_then(Value::as_array).ok_or_else(|| crate::i18n::tr("render.error_scene_bodies").to_string())?; + if values.len() > solidcraft_engine::render::job::MAX_GPU_PATH_BODIES { + return Err(crate::i18n::tr("render.error_scene_body_limit").into()); + } + let targets: Vec = serde_json::from_value(Value::Array(values.clone())).map_err(|e| e.to_string())?; + if targets.iter().any(|t| { + t.ordinal >= solidcraft_engine::render::job::MAX_GPU_PATH_BODIES + || t.name.is_empty() + || t.name.len() > 1024 + || t.name.chars().any(char::is_control) + }) { + return Err(crate::i18n::tr("render.error_scene_identity").into()); + } + Ok(targets) +} + +pub(super) fn revalidate(app: &mut SolveApp, binding: &mut Binding) -> Result<(), String> { + let targets = read_targets(app)?; + if !targets.contains(&binding.target) { + return Err(app.tr("render.material_target_missing").to_string()); + } + binding.revision = app.session.revision; + binding.document = Arc::downgrade(&app.session.doc); + Ok(()) +} + +/// Called for every Check and Start through the one shared image request builder. +/// No files are read until the engine captures the actual request. +pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { + let view = &app.render_workspace.view.materials; + if !view.enabled || !view.bindings.iter().any(Binding::active) { + return Ok(()); + } + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + if !cpu_optics_active(app) { + return Err(app.tr("render.cpu_optics_explicit").into()); + } + return cpu_params(app, params); + } + if app.render_workspace.view.method != super::ImageMethod::GpuRaytrace { + return Err(app.tr("render.material_gpu_required").to_string()); + } + if view.bindings.len() > MAX_BINDINGS { + return Err(app.tr("render.material_limits").to_string()); + } + let (mut glass, mut coats, mut textures) = (Vec::new(), Vec::new(), Vec::new()); + let mut seen = std::collections::BTreeSet::new(); + for binding in view.bindings.iter().filter(|b| b.active()) { + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").to_string()); + } + let target = &binding.target; + if target.ordinal >= solidcraft_engine::render::job::MAX_GPU_PATH_BODIES + || target.name.is_empty() + || target.name.len() > 1024 + || target.name.chars().any(char::is_control) + || !seen.insert(target.ordinal) + { + return Err(app.tr("render.material_target_missing").to_string()); + } + if binding.glass_enabled && (binding.coat_enabled || binding.maps_enabled) { + return Err(app.tr("render.material_glass_exclusive").to_string()); + } + let identity = || json!({"body_index":target.ordinal,"body_name":target.name}); + if binding.glass_enabled { + let value = &binding.glass; + OpaqueSurface::new(Vec3::ZERO, 0.0, 0.5, value.ior).map_err(|e| e.to_string())?; + let [r, g, b] = value.absorption; + Transmission::new(Vec3::new(r, g, b), (value.boundary == Boundary::Thin).then_some(value.thickness)).map_err(|e| e.to_string())?; + let mut wire = identity(); + wire["ior"] = json!(value.ior); + wire["absorption_per_mm"] = json!(value.absorption); + wire["boundary"] = json!(value.boundary.wire()); + wire["thickness_mm"] = json!(if value.boundary == Boundary::Thin { value.thickness } else { 0.0 }); + wire["shadow_transmission"] = json!(value.shadows); + if let Some(subsurface) = value.subsurface { + Transmission::new(Vec3::new(r, g, b), (value.boundary == Boundary::Thin).then_some(value.thickness)) + .map_err(|e| e.to_string())? + .with_shadow_transmission(value.shadows) + .with_subsurface(subsurface) + .map_err(|e| e.to_string())?; + wire["subsurface"] = json!(subsurface); + } + glass.push(wire); + } + if binding.coat_enabled { + let value = &binding.coat; + ClearCoat::new(value.weight, value.roughness, value.ior).map_err(|e| e.to_string())?; + let mut wire = identity(); + wire["weight"] = json!(value.weight); + wire["roughness"] = json!(value.roughness); + wire["ior"] = json!(value.ior); + coats.push(wire); + } + if binding.maps_enabled { + let value = &binding.maps; + value.frame.validate().map_err(|e| e.to_string())?; + if value.color.is_empty() && value.normal.is_empty() && value.roughness.is_empty() && value.metallic.is_empty() { + return Err(app.tr("render.material_map_required").to_string()); + } + if !value.strength.is_finite() + || !(0.0..=1.0).contains(&value.strength) + || [&value.color, &value.normal, &value.roughness, &value.metallic].iter().any(|p| p.len() > 4096 || p.chars().any(char::is_control)) + { + return Err(app.tr("render.material_map_invalid").to_string()); + } + let mut wire = identity(); + wire["frame"] = json!(value.frame); + wire["normal_strength"] = json!(value.strength); + wire["base_color_mode"] = json!(value.base_color_mode); + wire["flip_v"] = json!(value.flip_v); + if !value.color.is_empty() { + wire["base_color_srgb"] = json!(value.color); + } + if !value.normal.is_empty() { + wire["normal_opengl"] = json!(value.normal); + } + if !value.roughness.is_empty() { + wire["roughness_linear"] = json!(value.roughness); + } + if !value.metallic.is_empty() { + wire["metallic_linear"] = json!(value.metallic); + } + textures.push(wire); + } + } + if glass.len() > solidcraft_engine::render::job::MAX_GPU_DIELECTRICS + || textures.len() > solidcraft_engine::render::job::textures::MAX_TEXTURE_BINDINGS + { + return Err(app.tr("render.material_limits").to_string()); + } + params["raytrace"] = json!({"dielectrics":glass,"clear_coats":coats,"textures":textures}); + Ok(()) +} + +/// CPU has a distinct typed wire contract. Selecting its route never changes +/// authored optics, scalar appearances, geometry or sampling to make them fit. +pub(super) fn cpu_optics_active(app: &SolveApp) -> bool { + let view = &app.render_workspace.view.materials; + view.enabled && view.bindings.iter().any(|binding| binding.active() && binding.cpu_optics) +} + +fn cpu_params(app: &SolveApp, params: &mut Value) -> Result<(), String> { + use solidcraft_engine::render::job::{DielectricBoundary, DielectricOptions, RaytraceOptions}; + let view = &app.render_workspace.view; + if view.materials.bindings.len() > MAX_BINDINGS { + return Err(app.tr("render.material_limits").into()); + } + if !view.draft.optics.is_empty() { + return Err(app.tr("render.cpu_optics_saved").into()); + } + let mut options: RaytraceOptions = + serde_json::from_value(params.get("raytrace").cloned().ok_or_else(|| app.tr("render.cpu_optics_request").to_string())?) + .map_err(|error| error.to_string())?; + if !options.dielectrics.is_empty() { + return Err(app.tr("render.cpu_optics_conflict").into()); + } + let count = view.materials.bindings.iter().filter(|binding| binding.active()).count(); + if count > 8 { + return Err(app.tr("render.cpu_optics_limit").into()); + } + let mut shadow_transmission = None; + for binding in view.materials.bindings.iter().filter(|binding| binding.active()) { + if !binding.cpu_optics { + return Err(app.tr("render.cpu_optics_explicit").into()); + } + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + if shadow_transmission.is_some_and(|selected| selected != binding.glass.shadows) { + return Err(app.tr("render.cpu_shadow_mixed").into()); + } + shadow_transmission = Some(binding.glass.shadows); + } + // The current producer has one global directional switch, not a per-body mask. + // Never erase an OFF assignment or change the separate global shadows control. + let shadow_transmission = shadow_transmission.unwrap_or(false); + if options.directional_shadow_transmission && !shadow_transmission { + return Err(app.tr("render.cpu_shadow_conflict").into()); + } + if shadow_transmission + && (!options.shadows + || options.environment.is_some() + || params.get("environment").is_some_and(|value| !value.is_null()) + || view.cpu.nested_media) + { + return Err(app.tr("render.cpu_optics_unsupported").into()); + } + // Match the same placement identity that render.scene used for selection. + // No mesh extraction/certificate/proxy is performed on the UI thread. + let state = app.session.model.state(); + let frames = app.session.doc.body_frames_with_source(&state); + let world = app.session.world_state(); + let mut dielectrics = Vec::new(); + dielectrics.try_reserve_exact(count).map_err(|_| app.tr("render.material_limits").to_string())?; + for binding in view.materials.bindings.iter().filter(|binding| binding.active()) { + let target = &binding.target; + let stable = target.stable_target.as_ref().ok_or_else(|| app.tr("render.material_target_missing").to_string())?; + stable.validate().map_err(|error| error.to_string())?; + let mut bodies = + world.bodies.iter().filter(|body| app.session.body_visible(&body.name)).enumerate().filter(|(_, body)| body.name == target.name); + let (ordinal, body) = bodies.next().ok_or_else(|| app.tr("render.material_target_missing").to_string())?; + let matching_frames = frames + .iter() + .filter(|(name, definition, component, path, _)| { + name == &target.name && definition == &stable.definition && component == &stable.component && path == &stable.occurrence_path + }) + .count(); + if bodies.next().is_some() + || ordinal != target.ordinal + || body.feature != stable.feature + || body.definition_name() != stable.definition + || matching_frames != 1 + || target.name.is_empty() + || target.name.len() > 1024 + || target.name.chars().any(char::is_control) + { + return Err(app.tr("render.material_target_missing").into()); + } + if !binding.glass_enabled || binding.coat_enabled || binding.maps_enabled || binding.glass.subsurface.is_some() { + return Err(app.tr("render.cpu_optics_unsupported").into()); + } + let boundary = match binding.glass.boundary { + Boundary::Thin => DielectricBoundary::ThinSheet, + Boundary::Box => DielectricBoundary::ClosedBox, + Boundary::Closed => return Err(app.tr("render.cpu_optics_boundary").into()), + }; + dielectrics.push(DielectricOptions { + body_index: ordinal, + body_name: target.name.clone(), + boundary, + ior: binding.glass.ior, + absorption_per_mm: binding.glass.absorption, + thickness_mm: if boundary == DielectricBoundary::ThinSheet { binding.glass.thickness } else { 0.0 }, + }); + } + options.dielectrics = dielectrics; + options.directional_shadow_transmission = shadow_transmission; + // The composed typed request, not the editor's sampling label, decides + // sampling compatibility. Progressive optics requires the separately + // reviewed producer; geometry and installed capability still need admission. + options.validate().map_err(|error| error.to_string())?; + // Commit only the fully validated composition. Capture/admission still owns + // opacity, triangle certification, nesting and all resource/capability gates. + let wire = serde_json::to_value(options).map_err(|error| error.to_string())?; + params["raytrace"] = wire; + params["nested_media"] = json!(view.cpu.nested_media); + Ok(()) +} + +fn vector(app: &SolveApp, ui: &mut egui::Ui, key: &str, values: &mut [f64; 3], range: std::ops::RangeInclusive, suffix: &str) -> bool { + ui_kit::row(ui, app.tr(key), |ui| ui_kit::vector3_field(ui, values, range, suffix)) +} + +pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let title = app.tr("render.material_title").to_string(); + ui_kit::section(ui, "render_materials", &title, false, |ui| { + let mut view = std::mem::take(&mut app.render_workspace.view.materials); + ui.small(app.tr("render.material_transient")); + ui_kit::checkbox(ui, app.tr("render.material_enable"), &mut view.enabled); + if app.render_workspace.view.method == super::ImageMethod::Raster && view.enabled && view.bindings.iter().any(Binding::active) { + ui.colored_label(Tokens::get().warning, app.tr("render.material_gpu_required")); + } + if ui_kit::button(ui, app.tr("render.material_refresh"), ui_kit::Button::Normal).clicked() { + match read_targets(app) { + Ok(targets) => { + view.targets = targets; + view.target = None; + view.target_revision = Some(app.session.revision); + view.target_document = Some(Arc::downgrade(&app.session.doc)); + } + Err(e) => app.set_status(e, true), + } + } + let current = view.target_revision == Some(app.session.revision) + && view.target_document.as_ref().is_some_and(|doc| Weak::ptr_eq(doc, &Arc::downgrade(&app.session.doc))) + && !app.session.model.is_stale(); + ui_kit::bounded_cell_editor( + ui, + ui.id().with("render_material_search"), + &mut view.target_search, + app.tr("render.material_filter"), + false, + 128, + ); + let query = view.target_search.trim().to_lowercase(); + let label = + view.target.and_then(|i| view.targets.get(i)).map_or_else(|| app.tr("render.material_choose_body").to_string(), |t| t.name.clone()); + ui_kit::dropdown_menu(ui, "render_material_target", &label, |ui| { + for (index, target) in view.targets.iter().enumerate().filter(|(_, t)| t.name.to_lowercase().contains(&query)).take(128) { + if ui_kit::list_picker(ui, &format!("render:material-body-{}", target.ordinal), &target.name, view.target == Some(index)).clicked() { + view.target = Some(index); + ui.close(); + } + } + }); + let target = view.target.and_then(|index| view.targets.get(index)); + let existing = target.and_then(|target| view.bindings.iter().position(|binding| binding.target == *target)); + if ui_kit::button( + ui, + app.tr("render.material_add"), + ui_kit::Button::Enabled(current && target.is_some() && (existing.is_some() || view.bindings.len() < MAX_BINDINGS)), + ) + .clicked() + && let Some(target) = target.cloned() + { + view.selected = if let Some(index) = existing { + Some(index) + } else { + view.bindings.push(Binding::new(target, app)); + Some(view.bindings.len() - 1) + }; + view.enabled = true; + } + if view.targets.len() > 128 { + ui.small(app.tr("render.material_filter_help")); + } + if !current && !view.targets.is_empty() { + ui.small(app.tr("render.material_refresh_needed")); + } + let selected = view + .selected + .and_then(|i| view.bindings.get(i)) + .map_or_else(|| app.tr("render.material_assignments").to_string(), |b| b.target.name.clone()); + ui_kit::dropdown_menu(ui, "render_material_binding", &selected, |ui| { + for (index, binding) in view.bindings.iter().enumerate() { + if ui_kit::list_picker(ui, &format!("render:material-binding-{index}"), &binding.target.name, view.selected == Some(index)).clicked() + { + view.selected = Some(index); + ui.close(); + } + } + }); + let mut remove = false; + if let Some(binding) = view.selected.and_then(|index| view.bindings.get_mut(index)) { + ui.small(format!("{} · #{}", binding.target.name, binding.target.ordinal)); + ui_kit::checkbox(ui, app.tr("render.material_binding_enable"), &mut binding.enabled); + if !binding.current(app) { + ui.colored_label(Tokens::get().warning, app.tr("render.material_revalidate_needed")); + if ui_kit::button(ui, app.tr("render.material_revalidate"), ui_kit::Button::Normal).clicked() + && let Err(e) = revalidate(app, binding) + { + app.set_status(e, true); + } + } + remove |= editor_sections(app, ui, Some(binding)); + remove |= ui_kit::button(ui, app.tr("render.material_remove"), ui_kit::Button::Normal).clicked(); + } + if remove && let Some(index) = view.selected.filter(|i| *i < view.bindings.len()) { + view.bindings.remove(index); + view.selected = None; + } + ui.small(app.tr("render.material_limits")); + view.pending_remove = app.render_workspace.view.materials.pending_remove.take().or(view.pending_remove.take()); + app.render_workspace.view.materials = view; + }); +} + +fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) { + if ui_kit::checkbox(ui, app.tr("render.appearance_editor.glass_enable"), &mut binding.glass_enabled).changed() && binding.glass_enabled { + binding.coat_enabled = false; + binding.maps_enabled = false; + } + let recipes: Vec<_> = appearance_pack::STARTER_PACK.iter().filter(|p| matches!(p.recipe, Recipe::Glass(_))).collect(); + let name = + binding.glass.recipe.and_then(appearance_pack::find).map_or_else(|| app.tr("render.material_custom").to_owned(), |p| p.name.to_owned()); + let recipe_label = app.tr("render.appearance_editor.recipe").to_owned(); + ui_kit::row(ui, &recipe_label, |ui| { + let response = ui_kit::dropdown_menu(ui, "render_glass_recipe", &name, |ui| { + for preset in recipes { + let response = ui_kit::list_picker(ui, preset.id, preset.name, binding.glass.recipe == Some(preset.id)); + crate::scenario::publish_target(&format!("render:glass:{}", preset.id), response.rect); + if response.clicked() { + match Glass::recipe(preset.id) { + Ok(glass) => { + binding.glass = glass; + binding.glass_enabled = true; + binding.coat_enabled = false; + binding.maps_enabled = false; + } + Err(error) => app.set_status(error, true), + } + ui.close(); + } + } + }); + crate::scenario::publish_target("render:glass-recipe-select", response.rect); + }); + let glass = &mut binding.glass; + let mut changed = false; + ui.add_enabled_ui(binding.glass_enabled, |ui| { + let mut boundary = match glass.boundary { + Boundary::Closed => 0, + Boundary::Thin => 1, + Boundary::Box => 2, + }; + ui_kit::row(ui, app.tr("render.appearance_editor.boundary"), |ui| { + let labels = ["render.appearance_editor.closed", "render.appearance_editor.thin", "render.appearance_editor.box"].map(|key| app.tr(key)); + if ui_kit::segmented( + ui, + &mut boundary, + &labels, + ui_kit::Segments { + compact: true, + small: true, + targets: &["render:optics-boundary-closed", "render:optics-boundary-thin", "render:optics-boundary-box"], + ..Default::default() + }, + ) { + glass.boundary = match boundary { + 1 => Boundary::Thin, + 2 => Boundary::Box, + _ => Boundary::Closed, + }; + // Preserve CPU-incompatible intent until its own explicit edit. + // The existing GPU boundary defaults remain unchanged. + if app.render_workspace.view.method != super::ImageMethod::CpuRaytrace { + glass.shadows = glass.boundary == Boundary::Thin; + if glass.boundary == Boundary::Thin { + glass.subsurface = None; + } + } + changed = true; + } + }); + changed |= + ui_kit::row(ui, app.tr("render.appearance_editor.ior"), |ui| ui_kit::number_field(ui, &mut glass.ior, 1.0..=3.0, 0.01, "")).changed(); + ui.add_enabled_ui(glass.boundary == Boundary::Thin, |ui| { + changed |= ui_kit::row(ui, app.tr("render.appearance_editor.thickness"), |ui| { + ui_kit::number_field(ui, &mut glass.thickness, 0.001..=10000.0, 0.1, " mm") + }) + .changed(); + }); + changed |= vector(app, ui, "render.appearance_editor.absorption", &mut glass.absorption, 0.0..=100.0, " /mm"); + changed |= ui_kit::checkbox(ui, app.tr("render.material_shadow"), &mut glass.shadows).changed(); + ui.add_enabled_ui(glass.boundary != Boundary::Thin, |ui| { + let mut scatter = glass.subsurface.is_some(); + if ui_kit::checkbox(ui, app.tr("render.subsurface_enable"), &mut scatter).changed() { + glass.subsurface = + scatter.then_some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + changed = true; + } + if let Some(subsurface) = &mut glass.subsurface { + changed |= ui_kit::row(ui, app.tr("render.subsurface_rate"), |ui| { + ui_kit::number_field(ui, &mut subsurface.scattering_per_mm, 0.0..=100.0, 0.001, " /mm") + }) + .changed(); + changed |= ui_kit::row(ui, app.tr("render.volume_anisotropy"), |ui| { + ui_kit::number_field(ui, &mut subsurface.anisotropy, -0.95..=0.95, 0.01, "") + }) + .changed(); + } + }); + if glass.boundary != Boundary::Thin { + note(app, ui, "render.appearance_editor.thickness_reason"); + } + if glass.boundary == Boundary::Thin { + note(app, ui, "render.appearance_editor.scatter_reason"); + } + }); + if changed { + glass.recipe = None; + } + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + let response = ui_kit::checkbox(ui, app.tr("render.cpu_optics_enable"), &mut binding.cpu_optics); + crate::scenario::publish_target("render:cpu-optics-enable", response.rect); + let nested_label = app.tr("render.children.nested").to_owned(); + let response = ui_kit::checkbox(ui, &nested_label, &mut app.render_workspace.view.cpu.nested_media); + crate::scenario::publish_target("render:cpu-optics-nested", response.rect); + note(app, ui, "render.cpu_directional_shadow_help"); + } + note(app, ui, "render.appearance_editor.glass_note"); + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + note(app, ui, "render.cpu_optics_certification"); + } else { + note(app, ui, "render.material_certification"); + } +} + +fn coat_controls(app: &SolveApp, ui: &mut egui::Ui, binding: &mut Binding) { + ui_kit::checkbox(ui, app.tr("render.material_coat_enable"), &mut binding.coat_enabled); + ui.add_enabled_ui(binding.coat_enabled, |ui| { + for (key, value, range) in [ + ("render.appearance_editor.weight", &mut binding.coat.weight, 0.0..=1.0), + ("appearance.roughness", &mut binding.coat.roughness, 0.045..=1.0), + ] { + ui_kit::row(ui, app.tr(key), |ui| ui_kit::mixed_slider(ui, value, range, None)); + } + ui_kit::row(ui, app.tr("render.appearance_editor.ior"), |ui| ui_kit::number_field(ui, &mut binding.coat.ior, 1.0..=3.0, 0.01, "")); + }); +} + +#[derive(Clone, Copy)] +enum MapSlot { + Color, + Normal, + Roughness, + Metallic, +} +impl MapSlot { + fn key(self) -> &'static str { + match self { + Self::Color => "render.appearance_editor.base_colour", + Self::Normal => "render.appearance_editor.normal", + Self::Roughness => "appearance.roughness", + Self::Metallic => "appearance.metallic", + } + } + fn field(self, maps: &mut Maps) -> &mut String { + match self { + Self::Color => &mut maps.color, + Self::Normal => &mut maps.normal, + Self::Roughness => &mut maps.roughness, + Self::Metallic => &mut maps.metallic, + } + } +} +fn choose_map(app: &mut SolveApp, binding: &Binding, slot: MapSlot) { + let target = binding.target.clone(); + let origin = binding.document.clone(); + let revision = binding.revision; + app.pick_open_for(&["png", "jpg", "jpeg"], move |app, path| { + if !Weak::ptr_eq(&origin, &Arc::downgrade(&app.session.doc)) || app.session.revision != revision { + return; + } + if let Some(path) = path + && let Some(binding) = app + .render_workspace + .view + .materials + .bindings + .iter_mut() + .find(|b| b.target == target && b.revision == revision && Weak::ptr_eq(&b.document, &origin)) + { + *slot.field(&mut binding.maps) = path; + } + }); +} + +/// Prepare through the engine, then install only a request-local binding. No +/// authored material may silently remove a glass override or switch executor. +/// Read-only eligibility for an explicit catalogue action, not a certificate. +pub(super) fn library_glass_ready(app: &SolveApp, id: &str) -> Result<(), String> { + if !matches!(app.render_workspace.view.method, super::ImageMethod::CpuRaytrace | super::ImageMethod::GpuRaytrace) { + return Err(app.tr("render.glass_library_method").into()); + } + if id.is_empty() || id.len() > 128 { + return Err(app.tr("render.error_glass_recipe").into()); + } + let preset = appearance_pack::find(id).filter(|preset| preset.id == id).ok_or_else(|| app.tr("render.error_glass_recipe").to_string())?; + if !matches!(preset.recipe, Recipe::Glass(_)) { + return Err(app.tr("render.error_physical_glass").into()); + } + let [solidcraft_engine::Sel::Body { name }] = app.session.selection.as_slice() else { + return Err(app.tr("render.appearance_editor.body_reason").into()); + }; + if name.is_empty() || name.len() > 1024 || name.chars().any(char::is_control) || !app.session.body_visible(name) { + return Err(app.tr("render.material_target_missing").into()); + } + if app.session.model.is_stale() { + return Err(app.tr("render.material_revalidate_needed").into()); + } + let bindings = &app.render_workspace.view.materials.bindings; + let mut matching = bindings.iter().filter(|binding| binding.target.name == *name); + let existing = matching.next(); + if matching.next().is_some() { + return Err(app.tr("render.glass_library_conflict").into()); + } + if bindings.len() > MAX_BINDINGS || (existing.is_none() && bindings.len() == MAX_BINDINGS) { + return Err(app.tr("render.material_limits").into()); + } + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace + && existing.is_none_or(|binding| !binding.active()) + && bindings.iter().filter(|binding| binding.active()).count() >= 8 + { + return Err(app.tr("render.cpu_optics_limit").into()); + } + Ok(()) +} + +fn same_library_glass(a: &Glass, b: &Glass) -> bool { + a.recipe == b.recipe + && a.ior == b.ior + && a.absorption == b.absorption + && a.boundary == b.boundary + && a.thickness == b.thickness + && a.shadows == b.shadows + && a.subsurface.is_none() + && b.subsurface.is_none() +} + +/// Stage authored values in the existing editor. No appearance assignment, +/// implicit CPU permission, boundary inference, geometry certification or save. +pub(super) fn stage_library_glass(app: &mut SolveApp, id: &str) -> Result<(), String> { + library_glass_ready(app, id)?; + let glass = Glass::recipe(id)?; // The one existing validated conversion. + let [solidcraft_engine::Sel::Body { name }] = app.session.selection.as_slice() else { + return Err(app.tr("render.appearance_editor.body_reason").into()); + }; + let name = name.clone(); + let revision = app.session.revision; + let document = Arc::downgrade(&app.session.doc); + let targets = read_targets(app)?; + if revision != app.session.revision || !Weak::ptr_eq(&document, &Arc::downgrade(&app.session.doc)) || app.session.model.is_stale() { + return Err(app.tr("render.material_revalidate_needed").into()); + } + let mut matching = targets.into_iter().filter(|target| target.name == name); + let target = matching.next().ok_or_else(|| app.tr("render.material_target_missing").to_string())?; + if matching.next().is_some() { + return Err(app.tr("render.material_target_missing").into()); + } + target + .stable_target + .as_ref() + .ok_or_else(|| app.tr("render.material_target_missing").to_string())? + .validate() + .map_err(|error| error.to_string())?; + let existing = app.render_workspace.view.materials.bindings.iter().position(|binding| binding.target.name == name); + let binding = if let Some(index) = existing { + let old = app.render_workspace.view.materials.bindings.get(index).ok_or_else(|| app.tr("render.error_material_binding").to_string())?; + if old.target != target || !old.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + if old.coat_enabled || old.maps_enabled { + return Err(app.tr("render.glass_library_conflict").into()); + } + if same_library_glass(&old.glass, &glass) { + return Ok(()); // An exact repeat preserves ALL existing opt-ins and disabled state. + } + if old.glass_enabled || !same_library_glass(&old.glass, &Glass::default()) { + return Err(app.tr("render.glass_library_conflict").into()); + } + old.clone() // An empty existing slot retains its other authored fields/permission. + } else { + Binding::new(target, app) // New CPU permission remains false. + }; + let mut binding = binding; + binding.glass = glass; + binding.glass_enabled = true; + let view = &mut app.render_workspace.view.materials; + if let Some(index) = existing { + let slot = view.bindings.get_mut(index).ok_or_else(|| crate::i18n::tr("render.error_material_binding").to_string())?; + *slot = binding; + } else { + let was_empty = view.bindings.is_empty(); + view.bindings.try_reserve_exact(1).map_err(|_| crate::i18n::tr("render.material_limits").to_string())?; + view.bindings.push(binding); + if was_empty { + view.enabled = true; + } + // A previously disabled nonempty group is never reactivated by staging. + } + Ok(()) +} + +pub(super) fn install_library_surface(app: &mut SolveApp, id: &str, target: Target, plane: &str, scale: f64) -> Result<(), String> { + if app.render_workspace.view.method != super::ImageMethod::GpuRaytrace { + return Err(app.tr("render.material_gpu_required").into()); + } + let existing = app.render_workspace.view.materials.bindings.iter().position(|b| b.target == target); + if let Some(index) = existing { + let binding = + app.render_workspace.view.materials.bindings.get(index).ok_or_else(|| crate::i18n::tr("render.error_material_binding").to_string())?; + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + if binding.glass_enabled { + return Err(app.tr("render.material_glass_exclusive").into()); + } + } else if app.render_workspace.view.materials.bindings.len() >= MAX_BINDINGS { + return Err(app.tr("render.material_limits").into()); + } + let reply = + app.run("render.library.surface.prepare", json!({"id":id,"body_index":target.ordinal,"body_name":target.name,"plane":plane,"scale":scale}))?; + let texture = &reply["texture"]; + let frame: PlanarFrame = serde_json::from_value(texture["frame"].clone()).map_err(|e| e.to_string())?; + let path = |key: &str| texture[key].as_str().map(str::to_string).ok_or_else(|| crate::i18n::tr("render.error_surface_reply").to_string()); + let maps = Maps { + color: path("base_color_srgb")?, + normal: path("normal_opengl")?, + roughness: path("roughness_linear")?, + metallic: path("metallic_linear")?, + strength: 1.0, + frame, + base_color_mode: BaseColorMode::Replace, + flip_v: true, + }; + let mut binding = if let Some(index) = existing { + app.render_workspace + .view + .materials + .bindings + .get(index) + .cloned() + .ok_or_else(|| crate::i18n::tr("render.error_material_binding").to_string())? + } else { + Binding::new(target, app) + }; + binding.maps = maps; + binding.maps_enabled = true; + binding.enabled = true; + let view = &mut app.render_workspace.view.materials; + if let Some(index) = existing { + *view.bindings.get_mut(index).ok_or_else(|| crate::i18n::tr("render.error_material_binding").to_string())? = binding; + view.selected = Some(index); + } else { + view.bindings.try_reserve(1).map_err(|_| crate::i18n::tr("render.error_binding_allocation").to_string())?; + view.bindings.push(binding); + view.selected = Some(view.bindings.len() - 1); + } + view.enabled = true; + app.render_workspace.view.dirty = true; + Ok(()) +} + +fn map_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) { + ui_kit::checkbox(ui, app.tr("render.material_maps_enable"), &mut binding.maps_enabled); + ui.add_enabled_ui(binding.maps_enabled, |ui| { + for slot in [MapSlot::Color, MapSlot::Normal, MapSlot::Metallic, MapSlot::Roughness] { + let label = app.tr(slot.key()).to_owned(); + ui_kit::row(ui, &label, |ui| { + let path = slot.field(&mut binding.maps); + let label = if path.is_empty() { + app.tr("render.appearance_editor.choose_image").to_owned() + } else { + std::path::Path::new(path).file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default() + }; + if ui_kit::button(ui, &label, ui_kit::Button::Enabled(binding.current(app))).clicked() { + choose_map(app, binding, slot); + } + }); + } + vector(app, ui, "render.appearance_editor.origin", &mut binding.maps.frame.origin, -1e6..=1e6, " mm"); + vector(app, ui, "render.appearance_editor.u_repeat", &mut binding.maps.frame.u, -1e6..=1e6, " mm"); + vector(app, ui, "render.appearance_editor.v_repeat", &mut binding.maps.frame.v, -1e6..=1e6, " mm"); + ui_kit::row(ui, app.tr("render.appearance_editor.normal_strength"), |ui| { + ui_kit::mixed_slider(ui, &mut binding.maps.strength, 0.0..=1.0, None) + }); + ui_kit::checkbox(ui, app.tr("render.appearance_editor.v_up"), &mut binding.maps.flip_v); + let mut absolute = binding.maps.base_color_mode == BaseColorMode::Replace; + if ui_kit::checkbox(ui, app.tr("render.material_color_replace"), &mut absolute).changed() { + binding.maps.base_color_mode = if absolute { BaseColorMode::Replace } else { BaseColorMode::Modulate }; + } + }); +} + +fn save_optics(app: &mut SolveApp, binding: &Binding) -> Result<(), String> { + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + // A saved shot owns numerical intent, not the tab's local map/coat bindings. + // Keep those bindings intact while taking the portable shot snapshot. + let local = std::mem::take(&mut app.render_workspace.view.materials); + let setup = super::setups::snapshot(app); + app.render_workspace.view.materials = local; + let setup = setup?; + let value = &binding.glass; + let name = app.render_workspace.view.name.clone(); + let optics = json!({"ior":value.ior,"absorption_per_mm":value.absorption,"boundary":value.boundary.wire(), + "thickness_mm":if value.boundary==Boundary::Thin {value.thickness} else {0.0},"shadow_transmission":value.shadows,"subsurface":value.subsurface}); + app.run( + "render.optics.bind", + json!({"name":name,"set":setup,"body_index":binding.target.ordinal,"body_name":binding.target.name, + "optics":optics,"replace":binding.replace_saved_optics,"expected_revision":app.session.revision}), + )?; + let local = std::mem::take(&mut app.render_workspace.view.materials); + super::setups::load(app); + app.render_workspace.view.materials = local; + Ok(()) +} +fn note(app: &SolveApp, ui: &mut egui::Ui, key: &'static str) { + ui_kit::text(ui, app.tr(key), ui_kit::Text::Note(key)); +} + +/// The same body editor is used by the selection inspector and explicit-target page. +/// An unsupported selection gets an inert draft so every design control is inspectable. +fn editor_sections(app: &mut SolveApp, ui: &mut egui::Ui, binding: Option<&mut Binding>) -> bool { + let supported = binding.is_some(); + let mut placeholder = Binding::new(Target { stable_target: None, ordinal: 0, name: String::new() }, app); + let binding = binding.unwrap_or(&mut placeholder); + let reason = if !supported { + Some(app.tr("render.appearance_editor.body_reason").to_owned()) + } else if app.render_workspace.view.method != super::ImageMethod::GpuRaytrace { + Some(app.tr("render.appearance_editor.gpu_reason").to_owned()) + } else { + None + }; + let glass_reason = if supported && app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { None } else { reason.clone() }; + let glass_method = if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { "CPU" } else { "GPU" }; + let title = app.tr("render.appearance_editor.glass").to_owned(); + ui_kit::method_section(ui, "render:appearance:glass", &title, glass_method, glass_reason.as_deref(), |ui| glass_controls(app, ui, binding)); + let opaque_reason = reason.clone().or_else(|| binding.glass_enabled.then(|| app.tr("render.material_glass_exclusive").to_owned())); + let title = app.tr("render.appearance_editor.coat").to_owned(); + ui_kit::method_section(ui, "render:appearance:coat", &title, "GPU", opaque_reason.as_deref(), |ui| coat_controls(app, ui, binding)); + let title = app.tr("render.appearance_editor.maps").to_owned(); + ui_kit::method_section(ui, "render:appearance:maps", &title, "GPU", opaque_reason.as_deref(), |ui| map_controls(app, ui, binding)); + let title = app.tr("render.appearance_editor.saved").to_owned(); + let removed = ui_kit::editor_section(ui, "render:appearance:saved", &title, false, |ui| { + ui.add_enabled_ui(supported, |ui| saved_controls(app, ui, binding)).inner + }) + .unwrap_or(false); + reflection_section(app, ui, supported.then_some(binding.target.name.as_str())); + removed +} + +/// Resolve one selected whole body against the authoritative captured scene. Never +/// broaden a face/component selection into a whole-body optics assignment. +pub(super) fn selection_controls(app: &mut SolveApp, ui: &mut egui::Ui, body: Option<&str>) { + let mut binding = body.and_then(|name| app.render_workspace.view.materials.bindings.iter().find(|b| b.target.name == name).cloned()); + if binding.is_none() + && let Some(name) = body + { + let current = app.render_workspace.view.materials.target_revision == Some(app.session.revision) + && app.render_workspace.view.materials.target_document.as_ref().is_some_and(|d| Weak::ptr_eq(d, &Arc::downgrade(&app.session.doc))); + if !current { + match read_targets(app) { + Ok(targets) => { + let view = &mut app.render_workspace.view.materials; + view.targets = targets; + view.target_revision = Some(app.session.revision); + view.target_document = Some(Arc::downgrade(&app.session.doc)); + } + Err(error) => app.set_status(error, true), + } + } + let mut targets = app.render_workspace.view.materials.targets.iter().filter(|t| t.name == name); + if let Some(target) = targets.next() + && targets.next().is_none() + { + binding = Some(Binding::new(target.clone(), app)); + } + } + let before = app.session.revision; + let removed = editor_sections(app, ui, binding.as_mut()); + if let Some(binding) = binding { + let view = &mut app.render_workspace.view.materials; + let existing = view.bindings.iter().position(|b| b.target == binding.target); + if removed { + if let Some(index) = existing { + view.bindings.remove(index); + } + } else if app.session.revision == before { + // Opening the editor alone never allocates an inactive assignment. + if binding.glass_enabled || binding.coat_enabled || binding.maps_enabled || existing.is_some() { + if existing.is_none() { + view.enabled = true; + } + if let Some(index) = existing { + if let Some(slot) = view.bindings.get_mut(index) { + *slot = binding; + } + } else if view.bindings.len() < MAX_BINDINGS { + view.bindings.push(binding); + } else { + app.set_status(app.tr("render.material_limits").to_owned(), true); + } + } + } + } +} + +fn saved_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) -> bool { + let saved = app + .render_workspace + .view + .draft + .optics + .iter() + .enumerate() + .find(|(_, saved)| binding.target.stable_target.as_ref() == Some(&saved.target)) + .map(|(index, saved)| (index, saved.target.clone())); + ui_kit::banner(ui, ui_kit::AssistantTone::Working, |ui| { + note( + app, + ui, + if saved.is_some() && !binding.active() { "render.appearance_editor.saved_state" } else { "render.appearance_editor.temporary" }, + ); + }); + let can_save = binding.glass_enabled + && binding.current(app) + && !binding.maps_enabled + && !binding.coat_enabled + && app.render_workspace.view.method == super::ImageMethod::GpuRaytrace; + let mut removed = false; + ui.horizontal(|ui| { + let save = ui_kit::button(ui, app.tr("render.appearance_editor.save"), ui_kit::Button::Enabled(can_save)); + crate::scenario::publish_target("render:optics-save", save.rect); + if save.clicked() { + match save_optics(app, binding) { + Ok(()) => removed = true, + Err(error) => app.set_status(error, true), + } + } + let remove = ui_kit::button(ui, app.tr("render.appearance_editor.remove"), ui_kit::Button::Enabled(saved.is_some())); + crate::scenario::publish_target("render:optics-remove", remove.rect); + if remove.clicked() + && let Some((index, target)) = saved + { + crate::scenario::publish_target(&format!("render:optics-remove:{index}"), remove.rect); + app.render_workspace.view.materials.pending_remove = Some(PendingRemoval { + name: app.render_workspace.view.name.clone(), + target, + revision: app.session.revision, + document: Arc::downgrade(&app.session.doc), + }); + } + }); + ui_kit::checkbox(ui, app.tr("render.appearance_editor.replace"), &mut binding.replace_saved_optics); + if !can_save { + note(app, ui, "render.appearance_editor.save_reason"); + } + if !binding.current(app) { + note(app, ui, "render.material_revalidate_needed"); + } + if ui_kit::button(ui, app.tr("render.appearance_editor.revalidate"), ui_kit::Button::Normal).clicked() + && let Err(error) = revalidate(app, binding) + { + app.set_status(error, true); + } + super::library::saved_surface_target_controls(app, ui, binding.target.stable_target.as_ref()); + removed +} + +fn reflection_section(app: &mut SolveApp, ui: &mut egui::Ui, body: Option<&str>) { + let reason = if body.is_none() { + Some(app.tr("render.appearance_editor.body_reason").to_owned()) + } else if app.render_workspace.view.method != super::ImageMethod::CpuRaytrace { + Some(app.tr("render.appearance_editor.cpu_reason").to_owned()) + } else { + None + }; + let title = app.tr("render.appearance_editor.reflections").to_owned(); + ui_kit::method_section(ui, "render:appearance:reflections", &title, "CPU", reason.as_deref(), |ui| { + use solidcraft_engine::render::job::ReflectionMode; + let name = body.unwrap_or_default(); + let mut mode = app + .render_workspace + .view + .raytrace + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|b| b.body == name)) + .map_or(0, |b| if b.mode == ReflectionMode::Mirror { 1 } else { 2 }); + let labels = ["render.cpu_reflection_off", "render.cpu_reflection_mirror", "render.cpu_reflection_rough"].map(|key| app.tr(key).to_owned()); + let body_label = app.tr("render.inspector_this_body").to_owned(); + ui_kit::row(ui, &body_label, |ui| { + if ui_kit::segmented( + ui, + &mut mode, + &labels.each_ref().map(String::as_str), + ui_kit::Segments { compact: true, small: true, ..Default::default() }, + ) { + let value = match mode { + 1 => Some(ReflectionMode::Mirror), + 2 => Some(ReflectionMode::RoughSpecular), + _ => None, + }; + if let Err(error) = super::cpu::set_reflection(app, name, value) { + app.set_status(error, true); + } + } + }); + if ui_kit::button(ui, app.tr("render.cpu_binding_confirm"), ui_kit::Button::Enabled(mode != 0)).clicked() + && let Err(error) = super::cpu::revalidate(app, name) + { + app.set_status(error, true); + } + let title = app.tr("render.appearance_editor.reflection_sampling").to_owned(); + ui_kit::editor_section(ui, "render:appearance:reflection-sampling", &title, false, |ui| super::cpu::reflection_sampling_controls(app, ui)); + }); +} + +pub(super) fn confirmation_open(app: &SolveApp) -> bool { + app.render_workspace.view.materials.pending_remove.is_some() +} + +pub(super) fn confirmation(app: &mut SolveApp, ctx: &egui::Context) { + let Some(pending) = app.render_workspace.view.materials.pending_remove.clone() else { return }; + if pending.revision != app.session.revision + || pending.name != app.render_workspace.view.name + || !Weak::ptr_eq(&pending.document, &Arc::downgrade(&app.session.doc)) + { + app.render_workspace.view.materials.pending_remove = None; + app.set_status(app.tr("render.review_stale").to_owned(), true); + return; + } + let title = app.tr("render.appearance_editor.remove_title").to_owned(); + let (closed, action) = ui_kit::Confirm::new(egui::Id::new("render_remove_optics"), "delete", &title) + .tone(ui_kit::Tone::Danger) + .actions(app.tr("render.appearance_editor.remove"), app.tr("render.keep_editing"), None) + .selected(ui_kit::Action::Cancel) + .show(ctx, true, |ui| { + note(app, ui, "render.appearance_editor.remove_note"); + }); + if closed || action == ui_kit::Action::Cancel { + app.render_workspace.view.materials.pending_remove = None; + } + if action == ui_kit::Action::Ok { + app.render_workspace.view.materials.pending_remove = None; + match app.run("render.optics.unbind", json!({"name":pending.name,"target":&pending.target,"expected_revision":pending.revision})) { + Ok(_) => { + // Removing one saved binding must preserve unsaved shot settings + // and unrelated temporary overrides on this tab. + app.render_workspace.view.draft.optics.remove(&pending.target); + } + Err(error) => app.set_status(error, true), + } + } +} diff --git a/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_tests.rs b/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_tests.rs new file mode 100644 index 000000000..8d85f8dbd --- /dev/null +++ b/proposals/render/2026-10-31/cpu-directional-shadow-ui/candidate/crates/ui-egui/src/render_workspace_tests.rs @@ -0,0 +1,11297 @@ +use super::*; +use crate::scenario::Harness; +use solidcraft_engine::Session; + +fn environment_editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 1800.0))), events, ..Default::default() }, + |ui| { + ui.set_width(308.0); + environment::editor(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} + +fn environment_editor_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.settings.set", json!({"name":name,"set":{"job":{"method":"gpu_path","options":{"environment":{"kind":"sky"}}}}})).unwrap(); + setups::load(&mut h.app); + h +} + +#[test] +fn environment_editor_e4_variants_keep_all_five_sections_in_order() { + for variant in ["embedded", "sky", "file"] { + let mut h = environment_editor_fixture(); + if variant == "embedded" { + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + } else if variant == "file" { + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "C:/hdr/studio.hdr".into() }; + } else { + h.app.render_workspace.view.studio.backdrop_enabled = true; + } + let before = h.app.session.doc.clone(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let mut previous = -1.0; + let source_row = crate::scenario::rect_of("dialog:control:Source").unwrap(); + let change = crate::scenario::rect_of("render:environment:change").unwrap(); + assert!(source_row.contains_rect(change), "{variant}: Change must fit beside Source"); + for key in [ + "render.env_source", + "render.environment.orientation", + "render.env_backdrop", + "render.environment.ground", + "render.environment.atmosphere", + ] { + let rect = crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap(); + assert!(rect.top() > previous, "{variant}: {key} out of order"); + previous = rect.top(); + } + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + for key in [ + "render.environment.replace", + "render.environment.fit", + "render.environment.floor_wall", + "render.environment.cyclorama", + "render.environment.medium", + "render.environment.phase", + ] { + assert!(text.contains(h.app.tr(key)), "{variant}: missing {key}: {text}"); + } + for key in match variant { + "embedded" => &["render.environment.embedded", "render.environment.builtin"][..], + "file" => &["render.environment.choose", "render.environment.check"][..], + _ => &[ + "render.environment.zenith", + "render.environment.horizon", + "render.environment.sky_ground", + "render.environment.start", + "render.environment.end", + ][..], + } { + assert!(text.contains(h.app.tr(key)), "{variant}: missing {key}"); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "opening {variant} must never save"); + output.textures_delta.clear(); + } +} + +#[test] +fn environment_editor_unsupported_methods_keep_controls_and_reasons_without_switching() { + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + let mut h = environment_editor_fixture(); + h.app.render_workspace.view.method = method; + let before = h.app.session.doc.clone(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + for key in [ + "render.environment.needs_gpu", + "render.environment.gradient_gpu", + "render.environment.blur_pending", + "render.environment.world_pending", + "render.environment.medium", + "render.environment.min", + "render.environment.max", + ] { + assert!(text.contains(h.app.tr(key)), "missing {key}: {text}"); + } + output.textures_delta.clear(); + let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert!(h.app.render_workspace.view.studio.volume.is_none()); + assert_eq!(h.app.render_workspace.view.method, method); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + } +} + +#[test] +fn environment_editor_gradient_and_atmosphere_refuse_hostile_values_atomically() { + let mut h = environment_editor_fixture(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for value in [f64::NAN, f64::INFINITY, -1.0, 1e300] { + let mut gradient = h.app.render_workspace.view.studio.backdrop; + gradient.radius = value; + assert!(environment::commit_gradient(&mut h.app, true, gradient).is_err()); + h.app.render_workspace.view.studio.volume = + Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: value, ..Default::default() }); + assert!(setups::save(&mut h.app).is_err()); + h.app.render_workspace.view.studio.volume = None; + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + environment::commit_gradient(&mut h.app, true, Default::default()).unwrap(); + assert!(h.app.render_workspace.view.studio.backdrop_enabled); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); +} + +#[test] +fn environment_editor_stage_removal_requires_confirm_and_rejects_stale_answers() { + for stale in [false, true] { + let mut h = environment_editor_fixture(); + environment::commit_ground(&mut h.app, true, environment::Ground { margin: 1.0, gap: 0.1, color: [0.18; 3] }).unwrap(); + let before = h.app.session.doc.clone(); + environment::request_stage_removal(&h.app, &h.ctx); + for _ in 0..3 { + environment_editor_frame(&mut h, vec![]); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(crate::scenario::rect_of("dialog:ok").is_some()); + if stale { + h.app.run("render.settings.set", json!({"name":"Other","set":{"width":42}})).unwrap(); + } + let undo = h.app.session.undo.len(); + let at = crate::scenario::rect_of("dialog:ok").unwrap().center(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert_eq!(h.app.session.undo.len(), undo + usize::from(!stale)); + assert_eq!(h.app.render_workspace.view.draft.stage.is_empty(), !stale); + } +} + +#[test] +fn environment_editor_checked_file_embeds_bytes_and_keeps_the_recheck_banner() { + let mut h = environment_editor_fixture(); + let path = h.dir.join("environment-editor.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Gpu, path.to_string_lossy().into_owned()).unwrap(); + let undo = h.app.session.undo.len(); + environment::persist(&mut h.app); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + assert!(matches!(h.app.render_workspace.view.studio.hdr, hdr::Input::FileCaptured { .. })); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + assert!(crate::test_support::text_shapes(&output).any(|shape| shape.galley.job.text.contains(h.app.tr("render.environment.checked")))); + output.textures_delta.clear(); + let before = h.app.session.doc.clone(); + std::fs::write(&path, original_hdr_bytes(64, true)).unwrap(); + environment::persist(&mut h.app); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "changed bytes require rechecking"); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn environment_editor_medium_toggle_saves_one_command_without_a_gpu_host() { + let mut h = environment_editor_fixture(); + environment_editor_frame(&mut h, vec![]); + let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); + let undo = h.app.session.undo.len(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert!(h.app.render_workspace.view.studio.volume.is_some()); + assert_eq!(h.app.session.undo.len(), undo + 1); + let expected = setups::snapshot(&h.app).unwrap(); + assert_eq!(h.app.session.doc.render.setups[&h.app.render_workspace.view.name], expected); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.studio.volume.is_none()); +} + +#[test] +fn environment_ring_angles_snap_wrap_and_refuse_hostile_geometry() { + let center = egui::pos2(100.0, 200.0); + for (point, expected) in + [(egui::pos2(150.0, 200.0), 0.0), (egui::pos2(100.0, 250.0), 90.0), (egui::pos2(50.0, 200.0), 180.0), (egui::pos2(100.0, 150.0), -90.0)] + { + assert_eq!(environment::pointer_angle(point, center, 50.0), Some(expected)); + } + assert_eq!(environment::drag_rotation(170.0, 170.0, -170.0, false), Some(-170.0)); + assert_eq!(environment::drag_rotation(170.0, 0.0, 30.0, true), Some(-165.0)); + assert_eq!(environment::drag_rotation(-170.0, 0.0, -30.0, true), Some(165.0)); + assert_eq!(environment::drag_rotation(0.0, 0.0, 180.0, false), Some(-180.0)); + assert_eq!(environment::pointer_angle(center, center, 50.0), None); + for radius in [0.0, -1.0, f32::NAN, f32::INFINITY, 1e9] { + assert_eq!(environment::pointer_angle(egui::pos2(150.0, 200.0), center, radius), None); + } + for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(environment::pointer_angle(egui::pos2(value, 200.0), center, 50.0), None); + assert_eq!(environment::pointer_angle(center, egui::pos2(100.0, value), 50.0), None); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300] { + assert_eq!(environment::drag_rotation(value, 0.0, 20.0, false), None); + assert_eq!(environment::drag_rotation(0.0, value, 20.0, true), None); + assert_eq!(environment::drag_rotation(0.0, 0.0, value, false), None); + } +} + +fn environment_ring_frame(h: &mut Harness, mods: egui::Modifiers, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + focused: true, + events: std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(), + ..Default::default() + }, + |ui| { + let viewport = ui.max_rect(); + show(&mut h.app, ui); + environment_overlay(&mut h.app, ui, viewport); + }, + ); + output.textures_delta.clear(); +} + +fn environment_ring_fixture() -> Harness { + let mut h = environment_editor_fixture(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Environment; + h.app.preferences.nav = crate::prefs::OPENSCAD_NAV.into(); + h.app.cam.fit(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap().bounds); + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + h +} + +#[test] +fn render_workspace_frame_rect_fits_centres_and_refuses_hostile_sizes() { + let viewport = egui::Rect::from_min_size(egui::pos2(100.0, 40.0), egui::vec2(800.0, 600.0)); + for aspect in [16.0 / 9.0, 1.5, 1.0, 0.8, 9.0 / 16.0, 0.01, 100.0] { + let frame = shot::frame_rect(aspect, viewport).unwrap(); + assert!(viewport.contains_rect(frame)); + assert_eq!(frame.center(), viewport.center()); + assert!((f64::from(frame.width() / frame.height()) - aspect).abs() < 0.001); + assert!(frame.width() == viewport.width() || frame.height() == viewport.height()); + } + for aspect in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::MAX, 1e-300] { + assert!(shot::frame_rect(aspect, viewport).is_none()); + } + for size in [egui::Vec2::ZERO, egui::vec2(0.0, 400.0), egui::vec2(f32::NAN, 10.0), egui::vec2(f32::MAX, f32::MAX), egui::vec2(-10.0, 20.0)] { + assert!(shot::frame_rect(1.5, egui::Rect::from_min_size(egui::Pos2::ZERO, size)).is_none()); + } +} + +fn frame_editor_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1200})); + h.app.run("render.settings.set", json!({"name":"Hero","set":{"width":800,"height":600,"camera":h.app.cam}})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h +} + +#[test] +fn environment_ring_drag_is_one_undo_snaps_and_never_navigates_the_camera() { + use egui::{Event, Modifiers, PointerButton}; + let mut h = environment_ring_fixture(); + environment::commit_environment(&mut h.app, json!({"rotation_deg":170})).unwrap(); + environment_ring_frame(&mut h, Modifiers::NONE, vec![]); + let ring = h.app.render_workspace.view.environment_ring.geometry.unwrap(); + let at = |degrees: f32| ring.center + egui::vec2(degrees.to_radians().cos(), degrees.to_radians().sin()) * ring.radius; + let press = at(0.0); + let before = h.app.session.doc.clone(); + let camera = h.app.cam; + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + for pressed in [true, false] { + environment_ring_frame( + &mut h, + Modifiers::SHIFT, + vec![ + Event::PointerMoved(press), + Event::PointerButton { pos: press, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }, + ], + ); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "a Shift click without a drag does not snap or save"); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![ + Event::PointerMoved(press), + Event::PointerButton { pos: press, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + ], + ); + for angle in [10.0, 20.0, 30.0] { + environment_ring_frame(&mut h, Modifiers::SHIFT, vec![Event::PointerMoved(at(angle))]); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "drag is temporary"); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera, "OpenSCAD left-drag must not orbit through the ring"); + } + let end = at(30.0); + environment_ring_frame( + &mut h, + Modifiers::SHIFT, + vec![Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::SHIFT }], + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!((h.app.render_workspace.view.studio.rotation_rad.to_degrees() + 165.0).abs() < 1e-6); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert!(crate::scenario::rect_of("render:environment:ring-degrees").is_some()); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); +} + +#[test] +fn environment_ring_cancel_or_stale_revision_discards_the_drag() { + use egui::{Event, Modifiers, PointerButton}; + for stale in [false, true] { + let mut h = environment_ring_fixture(); + let ring = h.app.render_workspace.view.environment_ring.geometry.unwrap(); + let start = ring.center + egui::vec2(ring.radius, 0.0); + let end = ring.center + egui::vec2(0.0, ring.radius); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![ + Event::PointerMoved(start), + Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + ], + ); + environment_ring_frame(&mut h, Modifiers::NONE, vec![Event::PointerMoved(end)]); + if stale { + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":640}})).unwrap(); + } + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + let cancel = if stale { + vec![] + } else { + vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }] + }; + environment_ring_frame(&mut h, Modifiers::NONE, cancel); + environment_ring_frame(&mut h, Modifiers::NONE, vec![Event::PointerMoved(start)]); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], + ); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn environment_ring_visibility_follows_editor_target_and_live_canvas() { + let mut h = environment_ring_fixture(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + h.app.render_workspace.view.selection = RenderSelection::Environment; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_some()); + h.app.render_workspace.view.selection = RenderSelection::Nothing; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_none()); + h.app.render_workspace.view.inspector.page = inspector::Page::Environment; + h.app.render_workspace.view.result = true; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_none()); +} + +#[test] +fn environment_editor_opening_pages_and_sources_preserves_design_and_history() { + let mut h = environment_editor_fixture(); + let before = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for page in [inspector::Page::Environment, inspector::Page::Background] { + h.app.render_workspace.view.inspector.page = page; + environment_editor_frame(&mut h, vec![]); + assert!(crate::scenario::rect_of("render:environment:rotation-slider").is_some()); + h.app.ui.show_browser = false; + environment::open_sources(&mut h.app); + assert!(h.app.ui.show_browser); + assert_eq!(h.app.render_workspace.view.stage, Stage::Light); + assert_eq!(h.app.render_workspace.view.inspector.page, page); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + } +} + +#[test] +fn environment_editor_controls_commit_one_undo_each_and_refuse_hostile_edits() { + let mut h = environment_editor_fixture(); + for request in [json!({"rotation_deg":215}), json!({"intensity":2.5})] { + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + environment::commit_environment(&mut h.app, request).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + h.app.run("edit.redo", json!({})).unwrap(); + } + for (color, transparent) in [([40, 80, 120], false), ([40, 80, 120], true), ([40, 80, 120], false)] { + let undo = h.app.session.undo.len(); + environment::commit_backdrop(&mut h.app, color, transparent).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let mut ground = environment::Ground { margin: 0.25, gap: 0.1, color: [0.18; 3] }; + for edit in 0..5 { + match edit { + 1 => ground.margin = 1.0, + 2 => ground.gap = 0.25, + 3 => ground.color = [0.1, 0.3, 0.5], + _ => {} + } + let undo = h.app.session.undo.len(); + environment::commit_ground(&mut h.app, edit != 4, ground.clone()).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for request in [json!({"rotation_deg":1e300}), json!({"intensity":-1}), json!({"rotation_deg":"NaN"}), json!(null), json!([])] { + assert!(environment::commit_environment(&mut h.app, request).is_err()); + } + assert!(environment::commit_ground(&mut h.app, true, environment::Ground { gap: f64::NAN, ..ground }).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn environment_editor_slider_drag_commits_only_on_release() { + let mut h = environment_editor_fixture(); + environment_editor_frame(&mut h, vec![]); + let rect = crate::scenario::rect_of("render:environment:rotation-slider").unwrap(); + let start = rect.center(); + let end = egui::pos2(rect.right() - 20.0, start.y); + let undo = h.app.session.undo.len(); + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(start), + egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + ], + ); + environment_editor_frame(&mut h, vec![egui::Event::PointerMoved(end)]); + assert_eq!(h.app.session.undo.len(), undo, "dragging is temporary"); + environment_editor_frame( + &mut h, + vec![egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }], + ); + assert_eq!(h.app.session.undo.len(), undo + 1, "release saves one edit"); + environment_editor_frame(&mut h, vec![]); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn environment_editor_hdr_header_reads_catalog_without_applying_or_saving() { + let mut h = environment_editor_fixture(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(305.0, 1600.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let named = crate::test_support::text_shapes(&output).any(|text| text.galley.job.text.contains("Neutral side softbox")); + output.textures_delta.clear(); + assert!(named); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + for request in [json!({"rotation_deg":540}), json!({"intensity":0})] { + let undo = h.app.session.undo.len(); + environment::commit_environment(&mut h.app, request).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } +} + +#[test] +fn render_workspace_frame_opening_editor_and_presets_never_mutates_or_starts_a_job() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + h.frames(4); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(crate::scenario::rect_of("render:shot:name").is_some()); + assert!(crate::scenario::rect_of("render:frame:aspect:16:9").is_some()); + assert!(crate::scenario::rect_of("render:frame:overlay").is_some()); + assert_eq!(shot::selected(&h.app), Some("Hero")); + h.step(&json!({"click":{"handle":"render:frame:thirds"}})).unwrap(); + assert!(h.app.render_workspace.view.frame.guides.thirds); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + let mut h = frame_editor_fixture(); + let camera = Camera { fov: 175f64.to_radians(), ..h.app.cam }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.frames(4); + assert_eq!(h.app.cam, camera, "opening must preserve valid FOVs outside the slider's usual editing range"); +} + +#[test] +fn render_workspace_frame_guides_are_transient_and_overlay_visibility_is_contextual() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.app.run("view.render_frame", json!({"aspect":"16:9","thirds":true,"safe_area":true,"centre_mark":true})).unwrap(); + assert!(shot::overlay_visible(&h.app)); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)); + let frame = shot::preview_rect(&h.app, viewport).unwrap(); + assert!((frame.width() / frame.height() - 16.0 / 9.0).abs() < 0.001); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + assert!(!shot::overlay_visible(&h.app)); + h.app.render_workspace.view.inspector.page = inspector::Page::Camera; + assert!(shot::overlay_visible(&h.app)); + h.app.render_workspace.view.result = true; + assert!(!shot::overlay_visible(&h.app)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.doc.render.setups["Hero"].width, 800); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.frame.guides.thirds); + assert!(h.app.render_workspace.view.frame.guides.safe_area); + assert!(h.app.render_workspace.view.frame.guides.centre_mark); +} + +#[test] +fn render_workspace_frame_exposure_drag_is_one_saved_edit_and_undoes() { + let mut h = frame_editor_fixture(); + shot::edit_settings(&mut h.app, "Hero", json!({"job":{"method":"cpu_raytrace"}})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0, "exposure track: {track:?}"); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.75, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + assert_ne!( + h.app.session.doc.render.setups["Hero"].exposure_ev, 0.0, + "track: {track:?}; state: {:?}; status: {:?}", + h.app.render_workspace.view.frame, h.app.status + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +#[test] +fn render_workspace_scene_render_shot_captures_current_size_and_live_camera_without_saving() { + let mut h = frame_editor_fixture(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + shot::edit_settings(&mut h.app, "Hero", json!({"width":16,"height":12})).unwrap(); + h.app.render_workspace.image_host = Some(solidcraft_engine::render::job::CpuHost::cooperative()); + sync_backend(&mut h.app); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let camera = Camera { distance: 85.0, fov: 35f64.to_radians(), ..h.app.cam }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.app.run("view.render_frame", json!({"thirds":true,"safe_area":true,"centre_mark":true})).unwrap(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("Hero")); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16384).unwrap(); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().unwrap(); + assert_eq!((frame.info.width, frame.info.height), (16, 12)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_workspace_frame_aspect_click_edits_only_selected_shot_size_once_and_undoes() { + let mut h = frame_editor_fixture(); + h.frames(4); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:frame:aspect:16:9"}})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert_eq!((saved.width, saved.height), (1920, 1080)); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + for (index, expected) in [(1, (1620, 1080)), (2, (1080, 1080)), (3, (864, 1080)), (4, (1080, 1920))] { + let undo = h.app.session.undo.len(); + shot::choose_aspect(&mut h.app, "Hero", index).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert_eq!((saved.width, saved.height), expected); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + shot::choose_aspect(&mut h.app, "Hero", 5).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert!(shot::choose_aspect(&mut h.app, "Hero", usize::MAX).is_err()); +} + +#[test] +fn render_workspace_frame_shot_edits_revert_duplicate_and_rename_use_existing_commands() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.render.setups["Hero"].clone(); + let camera = Camera { distance: before.camera.distance * 2.0, ..before.camera }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + let undo = h.app.session.undo.len(); + assert!(shots::camera_modified(&h.app, "Hero")); + shot::edit_settings(&mut h.app, "Hero", json!({"camera":camera})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(!shots::camera_modified(&h.app, "Hero")); + h.app.run("edit.undo", json!({})).unwrap(); + shot::revert(&mut h.app, "Hero").unwrap(); + assert_eq!(h.app.cam, before.camera); + shot::edit_settings(&mut h.app, "Hero", json!({"exposure_ev":1.5})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + shot::duplicate(&mut h.app, "Hero").unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 2); + let copied = h.app.session.doc.render.setups.iter().find(|(name, _)| name.as_str() != "Hero").unwrap().1; + assert_eq!(copied, &h.app.session.doc.render.setups["Hero"]); + shot::rename(&mut h.app, "Hero", "Renamed").unwrap(); + assert_eq!(shot::selected(&h.app), Some("Renamed")); + assert_eq!(h.app.session.undo.len(), undo + 3); + let before = h.app.session.doc.to_json(); + for patch in [json!({"width":0}), json!({"width":u32::MAX}), json!({"height":1e300}), json!({"exposure_ev":33}), json!({"exposure_ev":null})] { + assert!(shot::edit_settings(&mut h.app, "Renamed", patch).is_err()); + assert_eq!(h.app.session.doc.to_json(), before); + } +} + +fn render_lights_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"cpu_raytrace","options":{"lights":[ + {"direction":[0.6,0,0.8],"color":[1,0.5,0.25],"intensity":3}, + {"direction":[-0.8,0,0.6],"color":[0.25,0.5,1],"intensity":2} + ]}}}}), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + setups::load(&mut h.app); + h.app.pending_fit = None; + h +} + +#[test] +fn render_lights_solo_and_mute_filter_preview_and_render_copies_without_saving_or_history() { + let mut h = render_lights_fixture(); + let original = setups::snapshot(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let json = document.to_json(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.app.run("render.lights.solo", json!({"id":"directional:1","solo":true})).unwrap(); + assert_eq!(light::preview(&h.app).unwrap().len(), 1); + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["lights"][0]["intensity"], 0.0); + assert_eq!(request["settings"]["job"]["options"]["lights"][1]["intensity"], 2.0); + h.app.run("render.lights.mute", json!({"id":"directional:1","mute":true})).unwrap(); + assert!(light::preview(&h.app).unwrap().is_empty()); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["options"]["lights"][1]["intensity"], 0.0); + assert_eq!(setups::snapshot(&h.app).unwrap(), original); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.doc.to_json(), json); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + assert!(h.app.run("render.lights.mute", json!({"id":"area:0","mute":true})).is_err()); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.active()); +} + +#[test] +fn render_lights_editor_opening_and_disabled_gpu_types_never_edit_or_start_a_job() { + let mut h = render_lights_fixture(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{"area_lights":[ + {"center":[0,0,100],"u":[1000000,0,0],"v":[0,-1000000,0],"radiance":[0,0,0]} + ]}}}}}), + ) + .unwrap(); + setups::load(&mut h.app); + h.app.run("view.render_select", json!({"kind":"light","id":"area:0"})).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + h.step(&json!({"click":{"handle":"render:light:type:point"}})).unwrap(); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); + assert_eq!(light::rows(&h.app).unwrap()[0].geometry.kind(), "area"); +} + +#[test] +fn render_lights_edit_commands_refresh_selected_editor_and_keep_visibility_separate_from_undo() { + let mut h = render_lights_fixture(); + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + light::edit(&mut h.app, "render.lights.set", Some("directional:0"), Some(json!({"intensity_ev":2}))).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into())); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 4.0); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.session.doc, document); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 3.0); + light::edit(&mut h.app, "render.lights.duplicate", Some("directional:0"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:2".into())); + light::edit(&mut h.app, "render.lights.remove", Some("directional:2"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); +} + +#[test] +fn render_lights_fixed_studio_requests_carry_transient_weights_without_saving_them() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let history = h.app.session.undo.len(); + h.app.run("render.lights.solo", json!({"id":"directional:1","solo":true})).unwrap(); + let raster = image_request(&h.app).unwrap(); + assert_eq!(raster["studio_weights"], json!([0.0, 1.0, 0.0])); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + assert_eq!(image_request(&h.app).unwrap()["studio_weights"], json!([0.0, 1.0, 0.0])); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), history); + assert!(serde_json::to_value(setups::snapshot(&h.app).unwrap()).unwrap().get("studio_weights").is_none()); +} + +#[test] +fn render_lights_list_inspects_unsaved_ui_draft_without_applying_or_opening_anything() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.lights = + Some(vec![solidcraft_engine::render::job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 7.0 }]); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + let camera = h.app.cam; + let page = h.app.render_workspace.view.inspector.page; + let snapshot = setups::snapshot(&h.app).unwrap(); + let reply = h.app.run("render.lights.list", json!({"settings":snapshot})).unwrap(); + assert_eq!(reply["lights"].as_array().unwrap().len(), 1); + assert_eq!(reply["lights"][0]["id"], "directional:0"); + assert_eq!(reply["lights"][0]["name"], "Key"); + assert_eq!(reply["lights"][0]["intensity"], 7.0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + assert_eq!(h.app.render_workspace.view.inspector.page, page); + assert_eq!(setups::snapshot(&h.app).unwrap(), snapshot); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +mod async_path_host { + + #[test] + fn cpu_and_raster_render_entries_keep_gpu_setup_unstarted_across_document_reset() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + let mut h = Harness::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + h.app.render_workspace.defer_path_host("not requested".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + Err("a CPU/Raster method must not call this GPU factory".into()) + }); + select_image_method(&mut h.app, method); + sync_backend(&mut h.app); + enter(&mut h.app, true).unwrap(); + for _ in 0..3 { + sync_backend(&mut h.app); + } + // The synchronous state and retained factory prove that no worker was + // launched, even if a wrongly launched thread had not been scheduled yet. + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + + crate::documents::adopt(&mut h.app, Session::default()); + select_image_method(&mut h.app, method); + enter(&mut h.app, true).unwrap(); + sync_backend(&mut h.app); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(h.app.render_workspace.setup_key.as_deref(), Some("not requested")); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + } + + #[test] + fn explicit_gpu_selection_starts_once_and_keeps_its_receiver_across_document_changes() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut h = Harness::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let (started, seen) = mpsc::channel(); + let (release, wait) = mpsc::channel(); + h.app.render_workspace.defer_path_host("explicit request".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + started.send(()).unwrap(); + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + Err("deliberate device-free refusal".into()) + }); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + seen.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + assert!(h.app.render_workspace.pending_setup.is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + // A real in-progress factory is not abandoned or duplicated when a new + // document defaults back to Raster, or the user changes methods meanwhile. + crate::documents::adopt(&mut h.app, Session::default()); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + let duplicate_calls = calls.clone(); + h.app.render_workspace.defer_path_host("must not duplicate".into(), move || { + duplicate_calls.fetch_add(1, Ordering::SeqCst); + Err("unexpected duplicate preparation".into()) + }); + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + select_image_method(&mut h.app, method); + sync_backend(&mut h.app); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + release.send(()).unwrap(); + finish_setup(&mut h); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("expected deliberate refusal") }; + assert_eq!(error, "deliberate device-free refusal"); + + // A method change or new document does not become an automatic retry. + crate::documents::adopt(&mut h.app, Session::default()); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("document reset lost the original failure") }; + assert_eq!(error, "deliberate device-free refusal"); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + enter(&mut h.app, true).unwrap(); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("GPU selection lost the original failure") }; + assert_eq!(error, "deliberate device-free refusal"); + let retry_calls = calls.clone(); + h.app.render_workspace.defer_path_host("must not retry".into(), move || { + retry_calls.fetch_add(1, Ordering::SeqCst); + Err("unexpected replacement after terminal failure".into()) + }); + sync_backend(&mut h.app); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("terminal failure was replaced") }; + assert_eq!(error, "deliberate device-free refusal"); + assert!(h.app.render_workspace.pending_setup.is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + use super::*; + use solidcraft_engine::render::job; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + + /// Advertise the path capability without opening a device or rendering anything. + struct TestExecutor; + impl job::ImageExecutor for TestExecutor { + fn descriptor(&self) -> job::Result { + let mut descriptor = job::CpuHost::cooperative().descriptor()?; + descriptor.id = ExecutorId::new("test-path").unwrap(); + descriptor.profiles[0].features.push(solidcraft_engine::render::RenderFeature::Progressive); + Ok(descriptor) + } + fn admit(&self, _: &ProductScene, _: &job::ImageRequest, _: job::JobOptions) -> job::Result { + panic!("setup tests must not render") + } + fn begin(&self, _: ProductScene, _: job::ImageRequest, _: job::JobOptions, _: job::CancelToken) -> job::Result> { + panic!("setup tests must not render") + } + } + + fn panel_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + h + } + + fn finish_setup(h: &mut Harness) { + let deadline = Instant::now() + Duration::from_secs(10); + while matches!(h.app.render_workspace.path_host, PathHost::Preparing(..)) { + assert!(Instant::now() < deadline, "test setup worker did not finish"); + h.frames(1); + std::thread::sleep(Duration::from_millis(1)); + } + h.frames(3); + } + + #[test] + fn design_frames_and_document_reset_never_start_the_deferred_path_host() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut h = Harness::new(); + h.app.render_workspace.defer_path_host("selected viewport".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(5); + crate::documents::adopt(&mut h.app, Session::default()); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + finish_setup(&mut h); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + enter(&mut h.app, false).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn first_render_before_adapter_install_starts_once_when_the_adapter_arrives() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut h = panel_fixture(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + h.app.render_workspace.defer_path_host("late selected viewport".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + Err("deliberate device refusal".into()) + }); + sync_backend(&mut h.app); + finish_setup(&mut h); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Failed(_))); + h.app.render_workspace.defer_path_host("must not retry".into(), || panic!("failed setup retried")); + enter(&mut h.app, false).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_fallback_viewport_replaces_an_unstarted_factory_without_opening_the_old_device() { + let mut h = Harness::new(); + h.app.render_workspace.defer_path_host("old hardware adapter".into(), || panic!("superseded device opened")); + h.app.render_workspace.defer_path_host("selected safe-mode adapter".into(), || Err("selected adapter unavailable".into())); + h.frames(5); + assert_eq!(h.app.render_workspace.setup_key.as_deref(), Some("selected safe-mode adapter")); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + enter(&mut h.app, true).unwrap(); + finish_setup(&mut h); + let PathHost::Failed(message) = &h.app.render_workspace.path_host else { panic!("expected selected adapter result") }; + assert_eq!(message, "selected adapter unavailable"); + } + + #[test] + fn preparing_keeps_frames_responsive_then_registers_ready_host() { + let mut h = panel_fixture(); + let cpu_host = h.app.session.render_job_host().unwrap().clone(); + let (release, wait) = mpsc::channel(); + let (started, thread) = mpsc::channel(); + h.app.render_workspace.path_host.start(move || { + started.send(std::thread::current().id()).unwrap(); + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + assert_ne!(thread.recv_timeout(Duration::from_secs(10)).unwrap(), std::thread::current().id()); + // A second viewport installation cannot replace or duplicate setup. + h.app.render_workspace.path_host.start(|| panic!("setup started twice")); + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + assert!(!h.app.session.render_backend().executors.iter().any(|e| e.id.as_str() == "test-path")); + let transparent = h.app.tr("render.image_transparent").to_string(); + h.step(&json!({"widget":transparent})).unwrap(); + assert!(h.app.render_workspace.view.transparent); + // Replacing the current document must retain the receiver while setup waits. + crate::documents::adopt(&mut h.app, Session::default()); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + enter(&mut h.app, false).unwrap(); + release.send(()).unwrap(); + finish_setup(&mut h); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_none()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_ok()); + assert_eq!(h.app.session.render_backend().executors.iter().filter(|e| e.id.as_str() == "test-path").count(), 1); + assert!(h.app.session.render_job_host().unwrap().same_host(&cpu_host)); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + crate::documents::adopt(&mut h.app, Session::default()); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + assert_eq!(h.app.session.render_backend().executors.iter().filter(|e| e.id.as_str() == "test-path").count(), 1); + } + + /// The first setup on an adapter shows a spinner, the time so far and a note; a later one + /// a bar estimated from the time the first took, which the preferences keep. + #[test] + fn setup_progress_is_estimated_from_the_last_setup_on_the_adapter() { + let mut h = panel_fixture(); + h.app.render_workspace.setup_key = Some("Test GPU | Vulkan | 1.0".into()); + let (release, wait) = mpsc::channel::<()>(); + h.app.render_workspace.path_host.start(move || { + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(3); + let first = h.app.tr("render.gpu_path_first_setup").to_string(); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + assert!(h.widget(&first).is_some(), "the first setup explains the wait"); + assert!(h.widget("0:00").is_some(), "and counts the time"); + release.send(()).unwrap(); + finish_setup(&mut h); + let took = h.app.render_workspace.setup_seconds.get("Test GPU | Vulkan | 1.0").copied(); + assert!(took.is_some_and(|s| (0.0..10.0).contains(&s)), "{took:?}"); + + // The next start on the same adapter has an estimate, kept in the preferences. + let mut h = panel_fixture(); + h.app.load_prefs(&json!({"gpu_path_setup_seconds": {"Test GPU | Vulkan | 1.0": 120.0}}).to_string()); + h.app.render_workspace.setup_key = Some("Test GPU | Vulkan | 1.0".into()); + let (release, wait) = mpsc::channel::<()>(); + h.app.render_workspace.path_host.start(move || { + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(3); + assert!(h.widget(&first).is_none()); + assert!(h.widget("0:00 / ~2:00").is_some(), "a bar with the estimate"); + release.send(()).unwrap(); + finish_setup(&mut h); + let prefs: serde_json::Value = serde_json::from_str(&h.app.prefs()).unwrap(); + assert!(prefs["gpu_path_setup_seconds"]["Test GPU | Vulkan | 1.0"].as_f64().is_some_and(|s| s < 10.0)); + } + + #[test] + fn hostile_setup_times_are_ignored() { + let times = load_setup_seconds(&json!({"a": -1.0, "b": 1e300, "c": "slow", "d": 30.0})); + assert_eq!(times.into_iter().collect::>(), [("d".to_string(), 30.0)]); + let many: serde_json::Map = (0..100).map(|i| (format!("gpu {i}"), json!(1.0))).collect(); + assert_eq!(load_setup_seconds(&serde_json::Value::Object(many)).len(), MAX_SETUP_TIMES); + } + + #[test] + fn setup_error_is_visible_and_survives_document_reset() { + let mut h = panel_fixture(); + h.app.render_workspace.path_host.start(|| Err("test driver refused the device".into())); + finish_setup(&mut h); + let message = "GPU path tracer unavailable: test driver refused the device"; + assert!(h.widget(message).is_some()); + assert!(h.widget("GPU path tracer: compiling shaders…").is_none()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + assert!(h.app.session.render_job_host().is_some()); + completed_preview(&mut h, [200, 210, 220]); + crate::documents::adopt(&mut h.app, Session::default()); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget(message).is_some()); + h.app.render_workspace.path_host.start(|| panic!("failed setup retried on viewport install")); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Failed(_))); + } + + #[test] + fn disconnected_setup_is_reported_in_the_panel() { + let mut h = panel_fixture(); + let (tx, rx) = mpsc::channel(); + h.app.render_workspace.path_host = PathHost::Preparing(rx, Instant::now()); + drop(tx); + h.frames(3); + assert!(h.widget("GPU path tracer unavailable: setup worker stopped without returning a host").is_some()); + } + + #[test] + fn panicking_setup_is_reported_in_the_panel() { + let mut h = panel_fixture(); + h.app.render_workspace.path_host.start(|| panic!("simulated driver panic")); + finish_setup(&mut h); + assert!(h.widget("GPU path tracer unavailable: GPU path tracer setup panicked").is_some()); + } + + #[test] + fn registration_failure_is_reported_in_the_panel() { + let mut h = panel_fixture(); + // A different host with the same CPU descriptor cannot be registered twice. + h.app.render_workspace.path_host.start(|| Ok(job::CpuHost::cooperative())); + finish_setup(&mut h); + let PathHost::Failed(message) = &h.app.render_workspace.path_host else { panic!("duplicate executor must fail") }; + assert!(h.widget(&format!("GPU path tracer unavailable: {message}")).is_some()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn opaque_pbr_product_gpu_and_cpu_share_color_and_material_semantics() { + use solidcraft_engine::render::{ + StandardView, + job::{CancelToken, ImageRequest, ImageTask, TaskPoll}, + }; + let mut s = Session::default(); + s.execute("solid.sphere", &json!({"radius":10,"body_name":"Original sphere"})).unwrap(); + const SIZE: u32 = 256; + let mut previous = None; + for (metallic, roughness) in [(0.0, 0.2), (0.0, 0.65), (1.0, 0.2), (1.0, 0.65)] { + s.execute( + "appearance.assign", + &json!({"bodies":["Original sphere"],"color":"#b47846", + "pbr":{"metallic":metallic,"roughness":roughness,"dielectric_ior":1.5}}), + ) + .unwrap(); + let scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + let (key, gpu) = gpu_scene(&scene).unwrap(); + assert!(!gpu.pbr.is_empty() && gpu.tris.is_empty()); + assert_ne!(previous, Some(key)); + previous = Some(key); + let mut camera = Camera { fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Iso); + camera.fit(&scene.bounds); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye().to_f32(); + let mut task = ImageTask::new( + scene, + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + camera, + width: SIZE, + height: SIZE, + background: [255; 3], + transparent_background: false, + integrator: Default::default(), + raytrace: None, + }, + CancelToken::default(), + ) + .unwrap(); + let mut png = None; + for _ in 0..100_000 { + if let TaskPoll::Complete(bytes) = task.step(4096).unwrap() { + png = Some(bytes); + break; + } + } + let cpu = image::load_from_memory(&png.expect("bounded original fixture completes")).unwrap().to_rgba8(); + assert_eq!(cpu.dimensions(), (SIZE, SIZE)); + let cpu = cpu.into_raw(); + for srgb in [false, true] { + let Some(gpu) = crate::gpu::render_product_offscreen( + gpu.clone(), + None, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], 0.0], + SIZE, + srgb, + ) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let at = |pixels: &[u8], x: usize, y: usize| { + let i = (y * SIZE as usize + x) * 4; + [pixels[i], pixels[i + 1], pixels[i + 2]] + }; + let mut core = 0usize; + let mut error = 0usize; + let mut outliers = 0usize; + for y in 2..SIZE as usize - 2 { + for x in 2..SIZE as usize - 2 { + // Exclude antialiased silhouettes: CPU uses 2x supersampling, GPU uses 1x. + if (y - 1..=y + 1).any(|ny| (x - 1..=x + 1).any(|nx| at(&cpu, nx, ny) == [255; 3] || at(&gpu, nx, ny) == [255; 3])) { + continue; + } + let delta = at(&cpu, x, y).into_iter().zip(at(&gpu, x, y)).map(|(a, b)| usize::from(a.abs_diff(b))).collect::>(); + error += delta.iter().sum::(); + outliers += usize::from(delta.iter().any(|d| *d > 12)); + core += 1; + } + } + assert!(core > 1000); + let mean = error as f64 / (3 * core) as f64; + eprintln!("PBR m={metallic} r={roughness} srgb={srgb}: core={core}, mean={mean}, outliers={outliers}"); + assert!(mean < 2.0 && outliers * 100 < core * 2, "CPU/GPU color or material interpretation differs"); + } + } +} + +#[test] +fn control_render_export_respects_upstream_file_scope() { + let mut h = Harness::new(); + let root = h.dir.join("allowed"); + let outside = h.dir.join("outside"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let roots = json!([root.to_string_lossy()]); + let response = h.call("ui.workspace", json!({"workspace":"render","allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + let response = h.call("engine.execute", json!({"command":"render.start","params":{"settings":{"width":16,"height":16}},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + let job = response["result"]["job"].clone(); + for _ in 0..50 { + h.frames(1); + } + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "completed"); + for path in [outside.join("denied.png"), root.join("../outside/traversal.png")] { + for overwrite in [false, true] { + let response = h.call( + "engine.execute", + json!({"command":"render.export","params":{"job":job,"path":path,"overwrite":overwrite},"allow_paths":roots}), + ); + assert_eq!(response["ok"], false, "{response}"); + assert!(response.to_string().contains("outside the folders this agent may use"), "{response}"); + } + } + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + let path = root.join("allowed.png"); + let response = h.call("engine.execute", json!({"command":"render.export","params":{"job":job,"path":path},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + assert!(path.is_file()); + let original = std::fs::read(&path).unwrap(); + let response = h.call("engine.execute", json!({"command":"render.export","params":{"job":job,"path":path,"overwrite":true},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(std::fs::read(&path).unwrap(), original); +} + +#[test] +fn adopting_into_blank_document_resets_render_draft_and_preserves_hosts() { + let mut h = Harness::new(); + h.app.render_workspace.host = Some(host_executor(2048, true, 4).unwrap()); + sync_backend(&mut h.app); + h.app.render_workspace.view.name = "Old draft".into(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let mut incoming = Session::default(); + incoming.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + crate::documents::adopt(&mut h.app, incoming); + assert!(!active(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + assert!(h.app.session.render_job_host().is_some()); + assert_eq!(h.app.session.model.state().bodies.len(), 1); +} + +#[test] +fn clicked_image_controls_complete_cancel_and_export_without_dirtying_the_design() { + for language in ["en", "de", "ko", "ru"] { + let mut h = Harness::new(); + h.app.preferences.language = language.into(); + h.frames(1); + let check = h.app.tr("cmd.render_preflight").to_string(); + let start = h.app.tr("render.image_start").to_string(); + let export = h.app.tr("render.image_export").to_string(); + h.call("ui.resize", json!({"width":1600,"height":1400})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.dirty = true; + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":check})).unwrap(); + h.step(&json!({"widget":start})).unwrap(); + for _ in 0..50 { + h.frames(1); + if h.app.render_workspace.view.completed.is_some() { + break; + } + } + let good = h.app.render_workspace.view.completed.unwrap(); + h.step(&json!({"widget":export})).unwrap(); + assert!(h.dir.join("render.png").is_file()); + h.app.render_workspace.view.draft.width = 1024; + h.app.render_workspace.view.draft.height = 768; + h.step(&json!({"widget":start})).unwrap(); + assert!(job_ready(&h.app, "render.cancel").is_ok()); + h.step(&json!({"click":{"handle":"render:stage:render.cancel"}})).unwrap(); + h.frames(5); + assert_eq!(h.app.render_workspace.view.completed, Some(good)); + assert_eq!( + h.app.session.execute("render.status", &json!({"job":h.app.render_workspace.view.job})).unwrap()["progress"]["phase"], + "cancelled" + ); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + } +} + +#[test] +fn saved_camera_survives_frames_and_product_fit_ignores_selection() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Product"})).unwrap(); + h.app.run("solid.box", json!({"corner":[100,0,0],"length":10,"width":20,"height":5,"body_name":"Other"})).unwrap(); + let camera = Camera { up: solidcraft_engine::render::UpAxis::Y, roll: 0.2, ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"camera":camera,"background":[21,43,65]}})).unwrap(); + h.frames(3); + let design = h.app.cam; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + h.step(&json!({"widget":"Restore Saved Camera"})).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.draft.background, [21, 43, 65]); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Product".into() }]; + h.call("engine.execute", json!({"command":"view.fit","params":{}})); + h.frames(3); + let selected_fit = h.app.cam; + assert_product_fits_canvas(&h.app); + h.app.session.selection.clear(); + h.app.cam = camera; + h.call("engine.execute", json!({"command":"view.fit","params":{}})); + h.frames(3); + assert_eq!(h.app.cam, selected_fit, "Fit Product ignores the selected subset"); + enter(&mut h.app, false).unwrap(); + assert_eq!(h.app.cam, design); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn progressive_image_controls_route_to_the_registered_host() { + let host = solidcraft_gpu::select::Policy::from_env() + .and_then(|policy| solidcraft_gpu::select::pick(policy).ok_or_else(|| "no qualifying adapter".to_string())) + .and_then(|(adapter, _)| solidcraft_gpu::path::host_on_adapter(&adapter).map_err(|e| e.to_string())); + let host = match host { + Ok(host) => host, + Err(e) => { + let expected = !solidcraft_gpu::select::path_backends().is_empty(); + assert!(!expected || std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GPU unavailable: {e}"); + eprintln!("skipping progressive UI device test: {e}"); + return; + } + }; + let mut h = Harness::new(); + h.app.render_workspace.path_host = PathHost::Ready(host); + sync_backend(&mut h.app); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + h.call("ui.resize", json!({"width":1600,"height":1600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.samples = 4; + h.app.render_workspace.view.max_depth = 3; + h.app.render_workspace.view.seed = 7; + h.app.render_workspace.view.draft.exposure_ev = 0.5; + h.app.render_workspace.view.studio.tone_map = solidcraft_engine::render::job::ToneMap::AcesFitted; + h.app.render_workspace.view.studio.lens_enabled = true; + h.app.render_workspace.view.studio.lens.aperture_radius_mm = 0.0; + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.ambient = [0.75; 3]; + // The UI request reaches the real registered host with a coat and captured map. + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut material = materials::Binding::new(target, &h.app); + material.coat_enabled = true; + material.maps_enabled = true; + let map_path = h.dir.join("original-color.png"); + image::RgbaImage::from_pixel(1, 1, image::Rgba([80, 160, 220, 255])).save(&map_path).unwrap(); + material.maps.color = map_path.to_string_lossy().into_owned(); + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(material); + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + let checked = image_params(&h.app).unwrap(); + assert_eq!(checked["raytrace"]["clear_coats"][0]["weight"], 1.0); + assert_eq!(checked["raytrace"]["textures"][0]["base_color_srgb"], map_path.to_string_lossy().as_ref()); + h.app.run("render.preflight", checked.clone()).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), checked); + let start = h.app.tr("render.image_start").to_string(); + h.step(&json!({"widget":start})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while h.app.render_workspace.view.completed.is_none() { + assert!(std::time::Instant::now() < deadline, "progressive UI job did not complete"); + std::thread::sleep(std::time::Duration::from_millis(5)); + h.frames(1); + } + let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(status["frame"]["executor"], "gpu-path", "{status}"); + assert_eq!(status["options"]["samples"], 4); + assert_eq!(status["options"]["max_depth"], 3); + assert_eq!(status["options"]["seed"], 7); + assert_eq!(status["options"]["exposure_ev"], 0.5); + assert_eq!(status["options"]["tone_map"], "aces_fitted"); + assert_eq!(status["options"]["lens"]["aperture_radius_mm"], 0.0); + assert_eq!(status["options"]["lighting"]["environment"], json!([0.75, 0.75, 0.75])); + assert_eq!(status["textures"]["bodies"], 1); + let export = h.app.tr("render.image_export").to_string(); + h.step(&json!({"widget":export})).unwrap(); + assert!(h.dir.join("render.png").is_file()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + // A pack glass recipe follows the same production request and passes actual + // closed-mesh preparation. It never calls scalar appearance assignment. + let material = &mut h.app.render_workspace.view.materials.bindings[0]; + material.coat_enabled = false; + material.maps_enabled = false; + material.glass_enabled = true; + material.glass = materials::Glass::recipe("starter.glass.clear-soda-lime").unwrap(); + let checked = image_params(&h.app).unwrap(); + h.app.run("render.preflight", checked.clone()).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), checked); + let started = h.app.run("render.start", checked).unwrap(); + let job = serde_json::from_value(started["job"].clone()).unwrap(); + let status = h.app.session.render_job_handle(job).unwrap().wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_engine::render::job::Phase::Completed, "{:?}", status.error); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn clicked_render_workspace_saves_one_setup_and_restores_design_view() { + for language in ["en", "de", "ko", "ru"] { + let mut h = Harness::new(); + h.app.preferences.language = language.into(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + h.frames(3); + let camera = h.app.cam; + let flags = (h.app.ui.show_grid, h.app.origin_shown(), h.app.ui.visual_style, h.app.ui.perspective); + let undo = h.app.session.undo.len(); + let at = crate::scenario::rect_of("workspace_switcher").unwrap().center(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + h.step(&json!({"click":{"handle":"menu:ui.workspace.render"}})).unwrap(); + assert!(active(&h.app)); + let heading = h.app.tr("render.page_scene").to_string(); + let perspective = h.app.tr("render.perspective").to_string(); + let save = h.app.tr("render.save_setup").to_string(); + let back = h.app.tr("render.return_design").to_string(); + assert!(h.widget(&heading).is_some(), "{language}"); + h.step(&json!({"click":{"handle":"render:scene:frame"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Camera); + h.step(&json!({"widget":perspective})).unwrap(); + assert!(!h.app.session.is_dirty(), "preview edits are staged"); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.setups["Studio"].camera, h.app.cam); + h.step(&json!({"widget":back})).unwrap(); + assert!(!active(&h.app)); + assert_eq!(h.app.cam, camera); + assert_eq!(flags, (h.app.ui.show_grid, h.app.origin_shown(), h.app.ui.visual_style, h.app.ui.perspective)); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!h.app.session.is_dirty()); + } +} + +#[test] +fn render_drafts_and_capabilities_are_isolated_across_document_switches() { + let mut h = Harness::new(); + h.app.render_workspace.host = Some(host_executor(2048, true, 4).unwrap()); + sync_backend(&mut h.app); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.render_workspace.view.name = "First draft".into(); + h.app.render_workspace.view.draft.background = [20, 40, 60]; + h.app.render_workspace.view.dirty = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(!active(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.render_workspace.view.name, "First draft"); + assert_eq!(h.app.render_workspace.view.draft.background, [20, 40, 60]); + assert!(h.app.render_workspace.view.dirty); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + h.app.run("file.new", json!({})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); +} + +#[test] +fn product_gpu_buffers_preserve_opacity_and_never_contain_overlays() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Glass"})).unwrap(); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.4})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + let (key, gpu) = gpu_scene(&scene).unwrap(); + assert!(gpu.tris.is_empty()); + assert!(!gpu.glass.is_empty()); + let color = |v: &[u8]| { + let i = v.get(crate::gpu::TRI_SIZE - 4..).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; + gpu.palette.get(crate::gpu::PaletteIndex(i)) + }; + assert!(gpu.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().all(|v| color(v) == Some([51, 102, 153, 102]))); + assert!(gpu.lines.is_empty() && gpu.overlay.is_empty() && gpu.under.is_empty() && gpu.hidden.is_empty() && gpu.ghost.is_empty()); + s.selection = vec![solidcraft_engine::Sel::Body { name: "Glass".into() }]; + s.section = Some((solidcraft_engine::geom::Vec3::ZERO, solidcraft_engine::geom::Vec3::X)); + let after = solidcraft_engine::product_scene::extract(&s).unwrap(); + assert_eq!(gpu_scene(&after).unwrap().0, key); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.0})).unwrap(); + let invisible = solidcraft_engine::product_scene::extract(&s).unwrap(); + assert_eq!(invisible.meshes[0].opacity, 0.0); + let (_, empty) = gpu_scene(&invisible).unwrap(); + assert!(empty.tris.is_empty() && empty.glass.is_empty()); +} + +#[test] +fn transmission_uses_legacy_preview_buffers_and_invalidates_the_opaque_cache() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Glass"})).unwrap(); + let appearance = json!({"bodies":["Glass"],"color":"#336699", + "pbr":{"metallic":0,"roughness":0.1,"dielectric_ior":1.5}}); + s.execute("appearance.assign", &appearance).unwrap(); + let (opaque_key, opaque) = gpu_scene(&solidcraft_engine::product_scene::extract(&s).unwrap()).unwrap(); + assert!(!opaque.pbr.is_empty()); + let mut scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + scene.meshes[0].transmission = + Some(solidcraft_engine::render::transmission::Transmission::new(solidcraft_engine::geom::Vec3::ZERO, None).unwrap()); + let (glass_key, glass) = gpu_scene(&scene).unwrap(); + assert_ne!(opaque_key, glass_key); + assert!(glass.pbr.is_empty()); + assert!(!glass.tris.is_empty()); + scene.meshes[0].opacity = 0.4; + let (_, transparent) = gpu_scene(&scene).unwrap(); + assert!(transparent.pbr.is_empty()); + assert!(!transparent.glass.is_empty()); +} + +#[test] +fn host_profiles_advertise_only_installed_opaque_pbr_not_hdri_refraction_or_final() { + use solidcraft_engine::render::*; + let host = host_executor(512, true, 4).unwrap(); + assert_eq!(host.limits.max_dimension, 512); + assert_eq!(host.profiles.len(), 1); + assert_eq!(host.profiles[0].features, vec![RenderFeature::Pbr]); + assert!(host.profiles[0].formats.is_empty()); + let mut s = Session::default(); + s.set_render_viewport(Some(host)).unwrap(); + let mut request = RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + width: 512, + height: 512, + format: None, + features: Vec::new(), + policy: Default::default(), + }; + assert_eq!(resolve_request(&[s.render_backend()], &request).unwrap().executor.as_str(), "gpu-viewport"); + request.features = vec![RenderFeature::Pbr]; + assert!(resolve_request(&[s.render_backend()], &request).is_ok()); + for unsupported in [RenderFeature::Hdri, RenderFeature::Refraction, RenderFeature::Progressive] { + request.features = vec![unsupported]; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + } + request.features.clear(); + request.width = 513; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + request.width = 512; + request.mode = RenderMode::Final; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + assert!(host_executor(1024, false, 1).unwrap().availability != Availability::Available); + assert!(host_executor(1024, true, 0).is_err()); +} + +fn completed_preview(h: &mut Harness, background: [u8; 3]) -> solidcraft_engine::render::job::JobId { + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":16,"height":16,"background":background}})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..100 { + host.pump(16384).unwrap(); + if h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "completed" { + return job; + } + } + panic!("small cooperative image did not complete within the work budget"); +} + +fn image_panel_frame(app: &mut SolveApp, ctx: &egui::Context) -> egui::FullOutput { + ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(285.0, 1200.0))), ..Default::default() }, + |ui| image_controls(app, ui), + ) +} + +#[test] +fn completed_image_is_painted_once_available_and_upload_is_cached() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert!(h.app.render_workspace.image.is_none()); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + let mut output = image_panel_frame(&mut h.app, &ctx); + let (cached_job, texture) = h.app.render_workspace.image.as_ref().unwrap(); + let texture = texture.as_ref().unwrap(); + let id = texture.id(); + assert_eq!(*cached_job, job); + assert_eq!(texture.size(), [16, 16]); + let uploaded = &output.textures_delta.set.get(&id).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + assert!(pixels.pixels.iter().all(|p| *p == Color32::from_rgb(20, 40, 60))); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + assert!( + ctx.tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| { matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id && !mesh.indices.is_empty()) }) + ); + let mut output = image_panel_frame(&mut h.app, &ctx); + assert!(!output.textures_delta.set.contains_key(&id), "repaint must reuse the texture"); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let path = h.dir.join("displayed.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png(), "displaying the image must not change export bytes"); +} + +#[test] +fn completed_image_keeps_last_export_during_work_and_updates_for_the_next_job() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(first); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + let old_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); + let pending = serde_json::from_value(reply["job"].clone()).unwrap(); + h.app.render_workspace.view.job = Some(pending); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, first); + h.app.run("render.cancel", json!({"job":pending})).unwrap(); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, first); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + let mut output = image_panel_frame(&mut h.app, &ctx); + let (cached_job, texture) = h.app.render_workspace.image.as_ref().unwrap(); + assert_eq!(*cached_job, second); + assert_ne!(texture.as_ref().unwrap().id(), old_texture); + assert!(output.textures_delta.free.contains(&old_texture)); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance = 42.0; + let framing = h.app.render_workspace.view.result_camera; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert!(h.app.render_workspace.image.is_none(), "another document must not show this image"); + assert!(!h.app.render_workspace.view.result); + crate::documents::switch(&mut h.app, 0); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, second); + assert!(h.app.render_workspace.view.result); + assert_eq!(h.app.render_workspace.view.result_camera, framing); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + reset_document(&mut h.app); + assert!(h.app.render_workspace.image.is_none()); + assert!(!h.app.render_workspace.view.result); +} + +#[test] +fn completed_image_decoder_preserves_alpha_and_rejects_invalid_sizes_and_pngs() { + let mut png = std::io::Cursor::new(Vec::new()); + let pixels = image::RgbaImage::from_pixel(2, 1, image::Rgba([80, 120, 160, 128])); + pixels.write_to(&mut png, image::ImageFormat::Png).unwrap(); + let decoded = decode_image(png.get_ref(), 2, 1).unwrap(); + assert_eq!(decoded.size, [2, 1]); + assert_eq!(decoded.pixels, vec![Color32::from_rgba_unmultiplied(80, 120, 160, 128); 2]); + for (width, height) in [(0, 1), (u32::MAX, 1), (4096, 4096), (1, 1), (3, 1)] { + assert!(decode_image(png.get_ref(), width, height).is_err(), "{width}x{height}"); + } + assert!(decode_image(b"invalid PNG", 2, 1).is_err()); +} + +#[test] +fn cpu_checkpoints_replace_only_the_provisional_texture_and_keep_final_export_and_framing() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.completed = Some(first); + h.app.render_workspace.view.job = Some(first); + cache_render_images(&mut h.app, &ctx); + let final_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let second = completed_preview(&mut h, [80, 100, 120]); + let frame = h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.job = Some(second); + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + remember_displayed_job(&mut h.app, false); + assert_eq!(displayed_image(&h.app).unwrap().info.job, second); + assert!(displayed_image(&h.app).unwrap().preview.is_some()); + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance = 123.0; + h.app.render_workspace.view.result_camera.target.x = 5.0; + let camera = h.app.render_workspace.view.result_camera; + let first_checkpoint = h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(); + // Repeated or older metadata never re-decodes bytes, even if passed bad data. + cache_preview_frame(&mut h.app, &ctx, &info, b"must not decode again"); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(), first_checkpoint); + info.frame_sequence = 2; + info.samples_per_pixel = 2; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + let newer = h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(); + assert_ne!(newer, first_checkpoint); + info.frame_sequence = 1; + cache_preview_frame(&mut h.app, &ctx, &info, b"out of order"); + remember_displayed_job(&mut h.app, false); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().info.frame_sequence, 2); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(), newer); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), final_texture); + assert_eq!(h.app.render_workspace.view.completed, Some(first)); + let path = h.dir.join("checkpoint-export-is-final.png"); + h.app.run("render.export", json!({"job":h.app.render_workspace.view.completed,"path":path})).unwrap(); + let retained = h.app.session.render_job_handle(first).unwrap().frame().unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), retained.png()); + // A final can arrive after the panel read a still-running status. The cached + // completed ID deliberately remains the old job until publication is sampled. + cache_render_images(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + assert!(displayed_image(&h.app).unwrap().preview.is_none()); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().job, second); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free, "a subsequent status refresh must not refit the new final"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn cancelling_a_preview_returns_to_the_final_image_without_resetting_pan_or_export() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + let final_job = completed_preview(&mut h, [30, 50, 70]); + h.app.render_workspace.view.completed = Some(final_job); + h.app.render_workspace.view.job = Some(final_job); + cache_render_images(&mut h.app, &ctx); + let frame = h.app.session.render_job_handle(final_job).unwrap().frame().unwrap().unwrap(); + let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); + let pending = serde_json::from_value(reply["job"].clone()).unwrap(); + h.app.render_workspace.view.job = Some(pending); + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + assert!(h.app.render_workspace.preview_image.is_none(), "a different job's checkpoint must be ignored"); + info.frame.job = pending; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + remember_displayed_job(&mut h.app, false); + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.target.x = 12.0; + h.app.render_workspace.view.result_camera.distance = 87.0; + let camera = h.app.render_workspace.view.result_camera; + h.app.run("render.cancel", json!({"job":pending})).unwrap(); + cache_render_images(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + assert_eq!(displayed_image(&h.app).unwrap().info.job, final_job); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + assert_eq!(h.app.render_workspace.view.completed, Some(final_job)); + assert!(h.app.run("render.export", json!({"job":pending,"path":h.dir.join("not-final.png")})).is_err()); + let path = h.dir.join("after-preview-cancel.png"); + h.app.run("render.export", json!({"job":final_job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + // Document adoption must also release a provisional texture without leaking it into a tab. + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + assert!(h.app.render_workspace.preview_image.is_some()); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(displayed_image(&h.app).is_none()); + assert!(h.app.render_workspace.preview_image.is_none()); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn result_framing_fits_both_axes_and_actual_size_respects_display_pixels() { + let canvas = egui::Rect::from_min_size(egui::pos2(40.0, 80.0), egui::vec2(800.0, 500.0)); + for size in [[1920, 1080], [100, 4000], [16, 16]] { + for dpi in [1.0, 1.5, 2.0] { + let fit = result_camera(size, canvas, dpi, ResultScale::Fit); + assert!(fit.is_valid()); + let fitted = result_rect(fit, size, canvas); + assert!(canvas.contains_rect(fitted), "{size:?} at {dpi}: {fitted:?}"); + assert_eq!(fitted.center(), canvas.center()); + let actual = result_rect(result_camera(size, canvas, dpi, ResultScale::Actual), size, canvas); + assert!((actual.width() * dpi - size[0] as f32).abs() < 0.01); + assert!((actual.height() * dpi - size[1] as f32).abs() < 0.01); + } + } +} + +#[test] +fn result_canvas_paints_large_capture_reports_staleness_and_preserves_export() { + let mut h = Harness::new(); + let ctx = crate::fonts::test_context(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.completed = Some(job); + h.app.render_workspace.view.result = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let preview = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + let draw = |app: &mut SolveApp| { + let mut out = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }, + |ui| show(app, ui), + ); + out.textures_delta.clear(); + out + }; + let out = draw(&mut h.app); + let id = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let current = h.app.tr("render.result_current"); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text() == current)); + let identity = format!("{}:{}:{}", job.session, job.serial, job.generation); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text().contains(&identity))); + let image_bounds = ctx + .tessellate(out.shapes, out.pixels_per_point) + .iter() + .filter_map(|p| match &p.primitive { + egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id => { + Some(mesh.vertices.iter().fold(egui::Rect::NOTHING, |r, v| r.union(egui::Rect::from_min_max(v.pos, v.pos)))) + } + _ => None, + }) + .fold(egui::Rect::NOTHING, |a, b| a.union(b)); + assert!(image_bounds.width() > 240.0 && image_bounds.height() > 240.0, "{image_bounds:?}"); + assert_eq!(h.app.cam, preview); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.session.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + let out = draw(&mut h.app); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text() == h.app.tr("render.image_stale"))); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().scene_generation, frame.info.scene_generation); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), id); + let path = h.dir.join("result-canvas.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); +} + +#[test] +fn result_navigation_uses_shared_pan_zoom_and_leaves_product_camera_unchanged() { + use egui::{Event, Key, Modifiers, PointerButton, vec2}; + let mut h = Harness::new(); + let ctx = crate::fonts::test_context(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.completed = Some(job); + h.app.render_workspace.view.result = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.ui.perspective = true; + h.app.preferences.smooth_wheel_zoom = false; + h.app.preferences.zoom_reverse = false; + let preview = h.app.cam; + let draft = serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(); + let dirty = h.app.render_workspace.view.dirty; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut time = 0.0; + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + let fitted = h.app.render_workspace.view.result_camera; + let p = h.app.viewport.rect.unwrap().center() + vec2(80.0, 20.0); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(p)]); + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 3.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + }], + ); + assert!(h.app.render_workspace.view.result_camera.distance < fitted.distance); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + let before_pan = h.app.render_workspace.view.result_camera.target; + let space = |pressed| Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![space(true), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], + ); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(p + vec2(40.0, -20.0))]); + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![ + Event::PointerButton { pos: p + vec2(40.0, -20.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + space(false), + ], + ); + assert_ne!(h.app.render_workspace.view.result_camera.target, before_pan); + assert_eq!(h.app.render_workspace.view.result_camera.pitch, fitted.pitch); + assert_eq!(h.app.render_workspace.view.result_camera.yaw, fitted.yaw); + let before_key = h.app.render_workspace.view.result_camera.target; + assert!(crate::navigation::view_key(&mut h.app, &ctx, Key::ArrowRight, Modifiers::CTRL, false)); + assert_ne!(h.app.render_workspace.view.result_camera.target, before_key); + assert!(!crate::navigation::view_key(&mut h.app, &ctx, Key::ArrowRight, Modifiers::NONE, false)); + for command in ["view.fit", "view.home"] { + h.app.render_workspace.view.result_camera.target.x += 20.0; + h.app.run(command, json!({})).unwrap(); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + assert_eq!(h.app.render_workspace.view.result_camera, fitted); + } + assert_eq!(h.app.cam, preview); + assert!(h.app.ui.perspective); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), draft); + assert_eq!(h.app.render_workspace.view.dirty, dirty); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(image_params(&h.app).unwrap()["settings"]["camera"], json!(preview)); +} + +#[test] +fn clicked_result_controls_switch_canvas_and_frame_without_changing_the_setup() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1400})); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let result = h.app.tr("render.result_title").to_string(); + h.step(&json!({"widget":result})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.result); + h.step(&json!({"widget":"100%"})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Actual); + let fit = h.app.tr("render.result_fit").to_string(); + h.step(&json!({"widget":fit})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Fit); + let preview = h.app.tr("render.result_preview").to_string(); + h.step(&json!({"widget":preview})).unwrap(); + assert!(!h.app.render_workspace.view.result); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); +} + +#[test] +fn image_method_requests_never_fall_back_or_mix_cpu_and_gpu_options() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_camera.distance = h.app.cam.distance * 3.0; + h.app.render_workspace.view.raytrace.exposure_ev = f64::NAN; + h.app.render_workspace.view.samples = 256; + h.app.render_workspace.view.max_depth = 12; + h.app.render_workspace.view.seed = 42; + h.app.render_workspace.view.draft.exposure_ev = 0.0; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "never-opened.hdr".into() }; + h.app.render_workspace.view.studio.denoise = true; + h.app.render_workspace.view.studio.lens_enabled = true; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "never-opened-cpu.hdr".into() }; + let params = image_params(&h.app).unwrap(); + assert_eq!(params["settings"]["camera"], json!(h.app.cam)); + assert_eq!(params["settings"]["exposure_ev"], 0.0); + for key in ["progressive", "samples", "max_depth", "seed", "integrator", "raytrace", "environment", "lighting", "tone_map", "lens", "denoise"] { + assert!(params.get(key).is_none(), "raster must omit {key}"); + } + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + assert!(image_params(&h.app).is_err(), "missing GPU cannot silently render on CPU"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + assert!(image_params(&h.app).is_err(), "unsupported CPU options or host must be refused"); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.session.set_render_job_host(None).unwrap(); + assert!(image_params(&h.app).is_err()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_cpu_controls_check_and_start_the_same_capture_and_keep_it_exportable() { + use solidcraft_engine::render::job::{CpuHost, Phase}; + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.dirty = true; + h.frames(3); + let available = image_host(&h.app, ImageMethod::CpuRaytrace).is_ok(); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-cpu"}})).unwrap(); + if !available { + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(image_params(&h.app).is_err()); + return; + } + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + h.step(&json!({"click":{"handle":"render:aa"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:aa-4"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + h.app.render_workspace.view.raytrace.preset = Some(LightingPreset::WarmCool); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + let numeric = image_params(&h.app).unwrap(); + assert_eq!(numeric["settings"]["job"]["method"], "cpu_raytrace"); + assert!(numeric.get("raytrace").is_none()); + let numeric_check = h.app.tr("cmd.render_preflight").to_string(); + h.step(&json!({"widget":numeric_check})).unwrap(); + assert_eq!(h.app.render_workspace.view.cpu.checked.as_ref().unwrap().request, numeric); + let reflected = h.app.session.world_state().bodies.first().unwrap().name.clone(); + let reflection_section = format!("dialog:section:{}", h.app.tr("render.cpu_reflections")); + h.step(&json!({"click":{"handle":reflection_section}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-reflection-body"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:{reflected}")}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-reflection-add"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("render:cpu-reflection-mode:{reflected}")}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:render.cpu_reflection_mirror"}})).unwrap(); + assert_eq!( + h.app.render_workspace.view.raytrace.reflections.as_ref().unwrap().bodies[0].mode, + solidcraft_engine::render::job::ReflectionMode::Mirror + ); + h.step(&json!({"click":{"handle":reflection_section}})).unwrap(); + let hdr_path = h.dir.join("cpu-captured.hdr"); + let mut hdr = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 1 +X 2\n".to_vec(); + hdr.extend_from_slice(&[128, 128, 128, 129, 128, 128, 128, 129]); + std::fs::write(&hdr_path, &hdr).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Cpu, hdr_path.to_string_lossy().into_owned()).unwrap(); + h.app.render_workspace.view.cpu.samples = 4; + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_camera.distance = 42.0; + h.frames(2); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let params = image_params(&h.app).unwrap(); + let preflight = h.app.session.execute("render.preflight", ¶ms).unwrap(); + assert_eq!(preflight["resolved"]["executor"], "cpu-raytrace"); + let check = h.app.tr("cmd.render_preflight").to_string(); + h.step(&json!({"widget":check})).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), params); + let checked = h.app.render_workspace.view.cpu.checked.as_ref().unwrap(); + assert_eq!(checked.request, params); + assert_eq!(checked.environment, preflight["environment"]); + let start = h.app.tr("render.image_start").to_string(); + h.step(&json!({"widget":start})).unwrap(); + let id = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + // The job owns the source bytes captured by Start, even if the file changes. + std::fs::write(&hdr_path, b"changed after capture").unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(json!(status.environment), preflight["environment"]); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.request.integrator, Integrator::Raytrace); + assert_eq!(json!(status.request.camera), params["settings"]["camera"]); + assert_eq!(json!(status.request.raytrace), params["raytrace"]); + assert_eq!(status.request.width, 16); + assert_eq!(status.request.height, 16); + h.frames(3); + assert_eq!(h.app.render_workspace.view.completed, Some(id)); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + let path = h.dir.join("cpu-result-canvas.png"); + h.app.run("render.export", json!({"job":id,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + h.app.render_workspace.view.transparent = true; + assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_opaque_required"))); + h.app.render_workspace.view.transparent = false; + h.app.render_workspace.view.raytrace.primary_samples = 3; + assert!(image_params(&h.app).is_err()); + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.area_lights = Some(Vec::new()); + assert_eq!(image_params(&h.app).unwrap()["raytrace"]["area_lights"], json!([])); +} + +fn async_export_fixture() -> (Harness, solidcraft_engine::render::job::JobId) { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + let job = completed_preview(&mut h, [200, 210, 220]); + (h, job) +} + +#[test] +fn delayed_image_export_holds_its_document_without_changing_history() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("delayed.png"); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(h.app.file_picker_busy() && !path.exists()); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["file_dialog_open"], true); + crate::documents::new_design(&mut h.app); + let other = h.app.session.doc.clone(); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(h.app.docs.active, 0, "upstream holds tab changes while a picker is pending"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["file_dialog_open"], false); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); + assert_eq!(&std::fs::read(&path).unwrap()[..8], b"\x89PNG\r\n\x1a\n"); + crate::documents::switch(&mut h.app, 0); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn delayed_image_export_cancel_and_overwrite_choice_preserve_existing_files() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("existing.png"); + std::fs::write(&path, b"existing contents").unwrap(); + let doc = h.app.session.doc.clone(); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!h.app.file_picker_busy()); + assert_eq!(std::fs::read(&path).unwrap(), b"existing contents"); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + h.app.render_workspace.view.overwrite = true; + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(std::fs::read(&path).unwrap(), b"existing contents", "a later checkbox change is not overwrite consent for the pending export"); + assert!(matches!(&h.app.status, Some((_, _, true)))); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "completed"); +} + +#[test] +fn delayed_image_export_never_substitutes_a_newer_retained_image() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("old-image.png"); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + let newer = completed_preview(&mut h, [20, 30, 40]); + h.app.render_workspace.view.completed = Some(newer); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!path.exists(), "the evicted requested image must fail instead of exporting the newer image"); + assert!(matches!(&h.app.status, Some((_, _, true)))); + assert_eq!(h.app.render_workspace.view.completed, Some(newer)); + let newer_path = h.dir.join("new-image.png"); + h.app.run("render.export", json!({"job":newer,"path":newer_path})).unwrap(); + assert!(newer_path.is_file()); +} + +#[test] +fn delayed_image_export_holds_close_and_new_document_until_cancel() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("closed.png"); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + crate::documents::new_design(&mut h.app); + crate::documents::close(&mut h.app, 0, true); + let other = h.app.session.doc.clone(); + assert_eq!(h.app.docs.count(), 1); + assert!(h.app.file_picker_busy()); + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!path.exists() && !h.app.file_picker_busy()); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); +} + +#[test] +fn delayed_image_export_refuses_an_internally_replaced_document_even_with_overwrite() { + use crate::picker_test_support::{Slot, save}; + for overwrite in [false, true] { + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("keep.png"); + std::fs::write(&path, b"keep this file").unwrap(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, overwrite); + assert!(h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":[1,2,3]})).is_err()); + // Internal host/session changes are outside the input hold; never export them by accident. + h.app.session.execute("appearance.assign", &json!({"bodies":["Body1"],"color":[1,2,3]})).unwrap(); + let changed = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.revision); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &crate::fonts::test_context()); + assert_eq!(std::fs::read(path).unwrap(), b"keep this file"); + assert!(Arc::ptr_eq(&changed, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.revision), history); + assert!(matches!(&h.app.status, Some((_, _, true)))); + } +} + +/// One frame of either the modelling viewport or the Render preview, over the same rectangle. +fn nav_frame(app: &mut crate::SolveApp, ctx: &egui::Context, render: bool, time: &mut f64, mods: egui::Modifiers, events: Vec) { + *time += 1.0 / 60.0; + let events = std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + time: Some(*time), + focused: true, + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + if render { + show(app, ui); + } else { + crate::viewport::show(app, ui); + } + }); + out.textures_delta.clear(); +} + +fn nav_app(render: bool, preset: &str, around: crate::prefs::OrbitAround) -> crate::SolveApp { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); + let mut app = crate::SolveApp::new(s, crate::Services::default()); + if render { + enter(&mut app, true).unwrap(); + assert!(active(&app)); + } + app.preferences.nav = preset.into(); + app.preferences.orbit_around = around; + app.preferences.zoom_to_cursor = true; + app.ui.perspective = true; + let mut cam = Camera { fov: 0.6, ..Default::default() }; + cam.set_view(solidcraft_engine::render::StandardView::Iso); + cam.fit(&solidcraft_engine::product_scene::extract(&app.session).unwrap().bounds); + app.cam = cam; + app +} + +/// #1454: the same mouse, wheel and modifier input moves the Render preview's camera exactly as +/// it moves the modelling viewport's, under every navigation preset and Orbit around setting. +#[test] +fn render_preview_navigates_like_the_modelling_viewport_in_every_preset() { + use egui::{Event, Modifiers, PointerButton, pos2, vec2}; + let none = Modifiers::NONE; + let chords = [none, Modifiers::SHIFT, Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT]; + let arounds = [crate::prefs::OrbitAround::ViewCentre, crate::prefs::OrbitAround::Cursor, crate::prefs::OrbitAround::Origin]; + for preset in crate::prefs::NAV_PRESETS.iter().map(|p| p.id) { + for around in arounds { + let (design_ctx, render_ctx) = (crate::fonts::test_context(), crate::fonts::test_context()); + let mut design = nav_app(false, preset, around); + let mut render = nav_app(true, preset, around); + let (mut design_time, mut render_time) = (0.0, 0.0); + let mut both = |events: Vec, mods: Modifiers, design: &mut crate::SolveApp, render: &mut crate::SolveApp| { + nav_frame(design, &design_ctx, false, &mut design_time, mods, events.clone()); + nav_frame(render, &render_ctx, true, &mut render_time, mods, events); + }; + both(vec![], none, &mut design, &mut render); + assert_eq!(design.viewport.rect, render.viewport.rect); + // Presses start on empty space in both workspaces, and the wheel + // turns over the model, so zoom to the cursor anchors on its surface. + let empty = pos2(90.0, 520.0); + let proj = crate::viewport::projection(&design, design.viewport.rect.unwrap()); + assert!(crate::viewport::pick(&design, &proj, empty).is_empty()); + let model = proj.to_screen(design.cam.target).unwrap(); + assert!(!crate::viewport::pick(&design, &proj, model).is_empty()); + let mut moved = 0; + for button in [PointerButton::Primary, PointerButton::Middle, PointerButton::Secondary] { + for mods in chords { + let before = design.cam; + both(vec![Event::PointerMoved(empty)], mods, &mut design, &mut render); + both(vec![Event::PointerButton { pos: empty, button, pressed: true, modifiers: mods }], mods, &mut design, &mut render); + let mut at = empty; + for _ in 0..5 { + at += vec2(14.0, -9.0); + both(vec![Event::PointerMoved(at)], mods, &mut design, &mut render); + } + both(vec![Event::PointerButton { pos: at, button, pressed: false, modifiers: mods }], mods, &mut design, &mut render); + for _ in 0..30 { + both(vec![], none, &mut design, &mut render); + } + assert_eq!(design.cam, render.cam, "{preset} {around:?}: {button:?} drag with {mods:?}"); + moved += usize::from(design.cam != before); + // Let any snap settle and start the next gesture from the same view. + design.cam = render.cam; + } + } + assert!(moved >= 2, "{preset}: the preset's drags move the camera ({moved})"); + // Wheel over the model, then modifier-only motion (Touchpad: Shift pans, Alt orbits). + let before = design.cam; + both(vec![Event::PointerMoved(model)], none, &mut design, &mut render); + let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, 3.0), modifiers: none, phase: egui::TouchPhase::Move }; + both(vec![wheel], none, &mut design, &mut render); + for _ in 0..30 { + both(vec![], none, &mut design, &mut render); + } + assert_ne!(design.cam, before, "{preset}: the wheel zooms"); + assert_eq!(design.cam, render.cam, "{preset} {around:?}: wheel zoom to the cursor"); + for mods in [Modifiers::SHIFT, Modifiers::ALT] { + both(vec![Event::PointerMoved(empty)], mods, &mut design, &mut render); + both(vec![Event::PointerMoved(empty + vec2(25.0, 15.0))], mods, &mut design, &mut render); + both(vec![Event::PointerMoved(empty)], none, &mut design, &mut render); + assert_eq!(design.cam, render.cam, "{preset} {around:?}: modifier motion with {mods:?}"); + } + assert!(render.session.selection.is_empty(), "camera navigation must not select"); + } + } +} + +/// #1454: Fit (F6), a middle double-click, and the axis view's and navigation cube's Home and +/// view controls all work in the Render workspace, framing the product scene. +#[test] +fn render_workspace_view_keys_double_middle_click_and_navigators_work() { + for style in [crate::prefs::NavigatorStyle::Axes, crate::prefs::NavigatorStyle::Cube] { + let mut h = Harness::new(); + h.app.preferences.navigator_style = style; + h.app.preferences.look_at_anim = false; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + let mut home = h.app.cam; + home.set_view(solidcraft_engine::render::StandardView::Iso); + let off = |h: &mut Harness| { + h.app.cam.yaw += 0.7; + h.app.cam.pitch = 0.1; + h.app.cam.distance *= 3.0; + h.app.cam.target.x += 25.0; + h.frames(2); + }; + // F6 fits, keeping the direction. + off(&mut h); + let before = h.app.cam; + h.step(&json!({"key":"F6"})).unwrap(); + h.settle(); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (before.yaw, before.pitch, before.roll, before.up), + "{style:?}: F6 retains orientation" + ); + assert!(h.app.cam.distance < before.distance, "{style:?}: F6 frames the product"); + assert_product_fits_canvas(&h.app); + // A middle double-click goes Home. + off(&mut h); + let centre = h.app.viewport.rect.unwrap().center(); + h.step(&json!({"click":[centre.x, centre.y], "double":true, "button":"middle"})).unwrap(); + h.settle(); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (home.yaw, home.pitch, home.roll, home.up), + "{style:?}: middle double-click" + ); + assert_product_fits_canvas(&h.app); + // The navigator's Home control. + off(&mut h); + let handle = match style { + crate::prefs::NavigatorStyle::Axes => "axis_view:home", + crate::prefs::NavigatorStyle::Cube => "navigation_cube:control:home", + }; + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.settle(); + assert!( + (h.app.cam.yaw - home.yaw).abs() < 1e-6 && (h.app.cam.pitch - home.pitch).abs() < 1e-6, + "{style:?}: navigator Home turns to the home view" + ); + // A standard view from the navigator. + h.step(&json!({"click":{"handle":"axis_view:z"}})).unwrap(); + h.settle(); + assert!(h.app.cam.back().dot(solidcraft_engine::geom::Vec3::Z) > 0.999, "{style:?}: view from +Z, got {:?}", h.app.cam.back()); + assert!(h.app.session.selection.is_empty()); + } +} + +/// #1464: a maximised 4K or 5K window is past the preview's pixel budget. The preview draws +/// smaller at the same aspect instead of refusing every frame. +#[test] +fn four_and_five_k_viewports_preview_downscaled_within_the_limits() { + use solidcraft_engine::render::*; + for samples in [1, 4, 16] { + let host = host_executor(16384, true, samples).unwrap(); + let mut s = Session::default(); + s.set_render_viewport(Some(host.clone())).unwrap(); + let request = |width, height| RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + width, + height, + format: None, + features: vec![RenderFeature::Pbr], + policy: Default::default(), + }; + if samples <= 4 { + assert_eq!(preview_size(s.render_viewport(), (1920, 1080)), (1920, 1080), "fits: drawn at full size"); + } + // 16× MSAA's scratch cost brings even 1080p under the budget. + let sizes: &[(u64, u64)] = if samples == 16 { &[(1920, 1080), (3840, 2160), (5120, 2880)] } else { &[(3840, 2160), (5120, 2880)] }; + for &full in sizes { + assert!(resolve_request(&[s.render_backend()], &request(full.0, full.1)).is_err(), "{full:?} at full size is over the limit"); + let (w, h) = preview_size(s.render_viewport(), full); + assert!(w < full.0 && h < full.1 && w * h <= host.limits.max_pixels, "{full:?} -> {w}x{h}"); + assert!((w as f64 / h as f64 - 16.0 / 9.0).abs() < 0.01, "{w}x{h} keeps the aspect"); + let resolved = resolve_request(&[s.render_backend()], &request(w, h)).unwrap(); + assert_eq!(resolved.executor.as_str(), "gpu-viewport"); + assert!(resolved.estimated_scratch_bytes <= host.limits.max_scratch_bytes); + } + } + assert_eq!(preview_size(None, (5120, 2880)), (5120, 2880), "no executor: resolution reports it"); +} + +/// Backend failures must remain readable in the fixed-width Render panel, not +/// disappear into an ellipsis before the reason and recovery guidance are shown. +#[test] +fn backend_diagnostics_wrap_without_elision_in_bounded_image_controls() { + fn collect<'a>(shape: &'a egui::Shape, texts: &mut Vec<&'a egui::epaint::TextShape>) { + match shape { + egui::Shape::Text(text) => texts.push(text), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, texts)), + _ => {} + } + } + for mode in ["floating", "compact"] { + for dark in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.dark = dark; + h.call("ui.resize", json!({"width":1400,"height":1800})); + h.app.run("view.layout", json!({"mode":mode})).unwrap(); + enter(&mut h.app, true).unwrap(); + let reason = "The selected viewport adapter has no compatible Vulkan path device. Images remain available on the CPU; keep the original design and review the driver before retrying."; + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + h.frames(3); + let expected = format!("{}: {reason}", h.app.tr("render.gpu_path_failed")); + let mut out = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1800.0))), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + ui.set_max_width(285.0); + image_controls(&mut h.app, ui); + }, + ); + out.textures_delta.clear(); + let mut texts = Vec::new(); + out.shapes.iter().for_each(|shape| collect(&shape.shape, &mut texts)); + { + let message = &expected; + let text = texts.iter().find(|text| text.galley.job.text == *message).expect("the complete diagnostic is painted"); + assert!(!text.galley.elided, "{mode}, dark={dark}: {message}"); + assert!(text.galley.rows.len() > 1, "long messages must wrap in the narrow panel"); + assert!(text.galley.rect.width() <= 285.0, "the message must not expand the panel"); + } + } + } +} + +#[test] +fn gpu_material_recipes_use_exact_linear_absorption_without_changing_saved_appearance() { + use solidcraft_engine::doc::appearance_pack::{GlassBoundary, Recipe, STARTER_PACK}; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); + h.app.session.mark_saved(); + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe(preset.id).unwrap(); + h.app.render_workspace.view.materials.bindings = vec![binding]; + let mut params = json!({"progressive":true}); + materials::params(&h.app, &mut params).unwrap(); + let wire = ¶ms["raytrace"]["dielectrics"][0]; + assert_eq!(wire["body_name"], "Optics"); + assert_eq!(wire["ior"], recipe.dielectric_ior); + let [r, g, b]: [f64; 3] = serde_json::from_value(wire["absorption_per_mm"].clone()).unwrap(); + let medium = solidcraft_engine::render::transmission::Transmission::new(solidcraft_engine::geom::Vec3::new(r, g, b), None).unwrap(); + let transmitted = medium.attenuation(recipe.reference_path_mm).unwrap(); + for (actual, expected) in [transmitted.x, transmitted.y, transmitted.z].into_iter().zip(recipe.transmission_linear_rgb) { + assert!((actual - expected).abs() < 1e-12, "the actual optical consumer must reproduce the recipe's linear transmittance"); + } + match recipe.boundary { + GlassBoundary::Closed => { + assert_eq!(wire["boundary"], "closed_mesh"); + assert_eq!(wire["thickness_mm"], 0.0); + } + GlassBoundary::Thin { thickness_mm } => { + assert_eq!(wire["boundary"], "thin_sheet"); + assert_eq!(wire["thickness_mm"], thickness_mm); + } + } + assert!(wire.get("opacity").is_none()); + count += 1; + } + assert_eq!(count, 6); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(materials::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.materials.enabled = false; + let mut raster = json!({}); + materials::params(&h.app, &mut raster).unwrap(); + assert!(raster.get("raytrace").is_none()); +} + +#[test] +fn gpu_material_identity_requires_explicit_revalidation_and_never_retargets() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.coat_enabled = true; + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; + materials::params(&h.app, &mut json!({})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(materials::params(&h.app, &mut json!({})).is_err()); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; + materials::params(&h.app, &mut json!({})).unwrap(); + h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[20,0,0],"body_name":"Other","operation":"new"})).unwrap(); + let scene = h.app.run("render.scene", json!({})).unwrap(); + let target: materials::Target = + serde_json::from_value(scene["bodies"].as_array().unwrap().iter().find(|body| body["name"] == "Other").unwrap().clone()).unwrap(); + let mut moved = materials::Binding::new(target.clone(), &h.app); + moved.coat_enabled = true; + h.app.render_workspace.view.materials.bindings = vec![moved.clone()]; + h.app.run("browser.visibility", json!({"items":["Optics"],"visible":false})).unwrap(); + assert!(materials::params(&h.app, &mut json!({})).is_err()); + assert!(materials::revalidate(&mut h.app, &mut moved).is_err(), "a surviving body with a new ordinal must be selected explicitly"); + assert_eq!(moved.target, target); + let scene = h.app.run("render.scene", json!({})).unwrap(); + assert_eq!(scene["bodies"][0]["name"], "Other"); + assert_ne!(scene["bodies"][0]["ordinal"], target.ordinal); + binding.target.name = "Different body".into(); + assert!(materials::revalidate(&mut h.app, &mut binding).is_err()); + assert_eq!(binding.target.name, "Different body"); + reset_document(&mut h.app); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); +} + +#[test] +fn clicked_gpu_glass_recipe_stays_temporary_and_blocks_cpu_rendering() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + h.app.session.mark_saved(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.frames(3); + let doc = h.app.session.doc.clone(); + let title = h.app.tr("render.material_title").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{title}")}})).unwrap(); + let refresh = h.app.tr("render.material_refresh").to_string(); + h.step(&json!({"widget":refresh})).unwrap(); + let choose = h.app.tr("render.material_choose_body").to_string(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:render:material-body-0"}})).unwrap(); + let add = h.app.tr("render.material_add").to_string(); + h.step(&json!({"widget":add})).unwrap(); + let glass = h.app.tr("render.appearance_editor.glass").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{glass}")}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.material_custom")})).unwrap(); + h.step(&json!({"click":{"handle":"render:glass:starter.glass.amber-tint"}})).unwrap(); + let binding = &h.app.render_workspace.view.materials.bindings[0]; + assert!(binding.glass_enabled && !binding.coat_enabled && !binding.maps_enabled); + assert_eq!(binding.glass.recipe, Some("starter.glass.amber-tint")); + assert_eq!(binding.target.name, "Optics"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + assert!(image_params(&h.app).is_err(), "CPU must not silently ignore active GPU material assignments"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn clicked_gpu_material_at_assignment_limit_edits_existing_but_cannot_add_another_body() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("solid.box", json!({"length":1,"width":1,"height":1,"body_name":"Optics"})).unwrap(); + h.app.run("solid.pattern.rectangular", json!({"bodies":["Optics"],"dir1":[1,0,0],"count1":129,"spacing1":3})).unwrap(); + let targets: Vec = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"].clone()).unwrap(); + assert_eq!(targets.len(), 129); + h.app.session.mark_saved(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.materials.bindings = targets.iter().skip(1).cloned().map(|target| materials::Binding::new(target, &h.app)).collect(); + h.frames(3); + let title = h.app.tr("render.material_title").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{title}")}})).unwrap(); + let refresh = h.app.tr("render.material_refresh").to_string(); + h.step(&json!({"widget":refresh})).unwrap(); + let choose = h.app.tr("render.material_choose_body").to_string(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:render:material-body-{}", targets[1].ordinal)}})).unwrap(); + let add = h.app.tr("render.material_add").to_string(); + h.step(&json!({"widget":add})).unwrap(); + let include = h.app.tr("render.material_binding_enable").to_string(); + h.step(&json!({"widget":include})).unwrap(); + assert!(!h.app.render_workspace.view.materials.bindings[0].enabled, "the existing assignment remains editable at the limit"); + assert!(h.app.render_workspace.view.materials.bindings.iter().skip(1).all(|binding| binding.enabled)); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 128); + + // The first scene body has no assignment: selecting it cannot create a 129th entry. + h.step(&json!({"widget":refresh})).unwrap(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:render:material-body-{}", targets[0].ordinal)}})).unwrap(); + h.step(&json!({"widget":add})).unwrap(); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 128); + assert!(h.app.render_workspace.view.materials.bindings.iter().all(|binding| binding.target != targets[0])); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn cpu_reflection_controls_preserve_exact_targets_and_engine_bounds() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + let reflections = h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap(); + assert_eq!(reflections.bodies.len(), 1); + reflections.max_bounces = 8; + reflections.samples = 64; + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["reflections"]["bodies"], json!([{"body":"Reflector","mode":"rough_specular"}])); + assert_eq!(params["raytrace"]["reflections"]["max_bounces"], 8); + assert_eq!(params["raytrace"]["reflections"]["samples"], 64); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().max_bounces = 9; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().max_bounces = 8; + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 65; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 64; + h.app.session.visibility.hidden_bodies.push("Reflector".into()); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_body_missing"))); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + assert!(h.app.render_workspace.view.raytrace.reflections.is_none()); + assert!(cpu::set_reflection(&mut h.app, "Missing", Some(ReflectionMode::Mirror)).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn cpu_reflection_binding_requires_confirmation_and_never_follows_a_reused_name() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("solid.box", json!({"length":5,"width":5,"height":5,"body_name":"Other"})).unwrap(); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!( + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap_err().contains(h.app.tr("render.cpu_binding_stale")) + ); + cpu::revalidate(&mut h.app, "Reflector").unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); + h.app.run("body.rename", json!({"body":"Reflector","name":"Original"})).unwrap(); + h.app.run("body.rename", json!({"body":"Other","name":"Reflector"})).unwrap(); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!(cpu::revalidate(&mut h.app, "Reflector").is_err(), "confirmation cannot move a binding to a different feature"); + let before = json!(h.app.render_workspace.view.raytrace.reflections); + for mode in [ReflectionMode::Mirror, ReflectionMode::RoughSpecular] { + assert!(cpu::set_reflection(&mut h.app, "Reflector", Some(mode)).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert_eq!(json!(h.app.render_workspace.view.raytrace.reflections), before, "a stale row's mode cannot rebind its body"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + } + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); + // Isolate document identity: the cloned document has the same bodies, IDs and revision. + let previous_doc = h.app.session.doc.clone(); + let previous_revision = h.app.session.revision; + h.app.session = Session::new((*previous_doc).clone()); + h.app.session.revision = previous_revision; + assert!(!Arc::ptr_eq(&previous_doc, &h.app.session.doc)); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); +} + +#[test] +fn cpu_interactive_reflection_binding_accepts_appearance_and_render_intent_without_qualifying_final() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + let world = h.app.session.world_state(); + let mesh = world.body("Reflector").unwrap().cached_mesh().unwrap(); + let document = h.app.session.doc.clone(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Reflector"],"color":"#123456"})).unwrap(); + assert!(!Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(Arc::ptr_eq(&mesh, &h.app.session.world_state().body("Reflector").unwrap().cached_mesh().unwrap())); + h.app.run("render.settings.set", json!({"name":"Interactive target proof","set":{"width":800,"height":600}})).unwrap(); + assert!(Arc::ptr_eq(&world, &h.app.session.world_state())); + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-opened-by-interactive-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = 0.25; + h.app.render_workspace.view.cpu.intensity = 2.0; + let before = json!(h.app.render_workspace.view.raytrace.reflections); + let mut interactive = json!({}); + cpu::params_interactive(&h.app, &mut interactive).unwrap(); + assert_eq!(interactive["raytrace"]["reflections"]["bodies"], json!([{"body":"Reflector","mode":"mirror"}])); + assert_eq!(interactive["raytrace"]["exposure_ev"], 1.5); + assert_eq!(interactive["environment"]["rotation_radians"], 0.25); + assert_eq!(interactive["environment"]["expected_sha256"], json!(h.app.render_workspace.view.cpu.hdr.resource().unwrap())); + assert_eq!(json!(h.app.render_workspace.view.raytrace.reflections), before); + assert!( + cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale")), + "Interactive refresh cannot qualify final Check/Start" + ); + assert!( + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).is_err(), + "mode changes still require explicit confirmation" + ); +} + +#[test] +fn cpu_interactive_binding_keeps_cold_meshes_cold_and_refuses_another_world_until_confirmation() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none()); + let retained = Arc::strong_count(&world); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none(), "request lowering must not tessellate"); + assert_eq!(Arc::strong_count(&world), retained, "the binding must not retain the evaluated world"); + h.app.session.execute("appearance.assign", &json!({"bodies":["Reflector"],"color":"#654321"})).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none()); + h.app.session.execute("solid.box", &json!({"length":3,"width":3,"height":3,"corner":[30,0,0],"body_name":"Other","operation":"new"})).unwrap(); + assert!(!Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + cpu::revalidate(&mut h.app, "Reflector").unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); +} + +#[test] +fn cpu_interactive_binding_refuses_reused_names_and_same_revision_in_a_new_document() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[30,0,0],"body_name":"Other","operation":"new"})).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("body.rename", json!({"body":"Reflector","name":"Original"})).unwrap(); + h.app.run("body.rename", json!({"body":"Other","name":"Reflector"})).unwrap(); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err()); + assert!(cpu::revalidate(&mut h.app, "Reflector").is_err()); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + let document = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let uid = h.app.session.uid; + h.app.session = Session::new((*document).clone()); + h.app.session.revision = revision; + assert_ne!(h.app.session.uid, uid); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err()); +} + +#[test] +fn cpu_interactive_binding_refuses_moved_occurrences_and_hidden_targets() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + let component = h.app.run("component.create", json!({"name":"Part","grounded":false})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + let name = world.bodies[0].name.clone(); + let mesh = world.bodies[0].mesh(); + cpu::set_reflection(&mut h.app, &name, Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[20,0,0]})).unwrap(); + let moved = h.app.session.world_state(); + assert!(!Arc::ptr_eq(&world, &moved)); + assert!(!Arc::ptr_eq(&mesh, &moved.bodies[0].mesh())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err(), "same creator and name cannot certify a moved instance"); + cpu::revalidate(&mut h.app, &name).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + h.app.session.visibility.hidden_bodies.push(name); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_body_missing"))); +} + +#[test] +fn cpu_interactive_binding_refuses_deleted_then_recreated_equal_looking_targets() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + let feature = world.body("Reflector").unwrap().feature; + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("timeline.delete", json!({"feature":feature.to_string()})).unwrap(); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + assert!(h.app.session.world_state().body("Reflector").is_some(), "the recreated case must actually reuse the selected name"); + assert!(!Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err(), "identical names/dimensions cannot certify recreated geometry"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); +} + +#[test] +fn cpu_environment_controls_keep_wire_schemas_separate_without_reading_files() { + let mut h = Harness::new(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-opened-by-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = std::f64::consts::FRAC_PI_2; + h.app.render_workspace.view.cpu.intensity = 2.0; + h.app.render_workspace.view.cpu.samples = 64; + let mut hdr = json!({}); + cpu::params(&h.app, &mut hdr).unwrap(); + assert_eq!( + hdr["environment"], + json!({"path":"not-opened-by-ui.hdr","expected_sha256":h.app.render_workspace.view.cpu.hdr.resource().unwrap(),"rotation_radians":std::f64::consts::FRAC_PI_2,"intensity":2.0,"samples":64}) + ); + assert!(hdr["raytrace"].get("environment").is_none()); + for gpu_key in ["progressive", "tone_map", "denoise", "lighting", "lens"] { + assert!(hdr.get(gpu_key).is_none()); + } + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [0.2, 0.4, 0.8]; + let mut constant = json!({}); + cpu::params(&h.app, &mut constant).unwrap(); + assert!(constant.get("environment").is_none()); + assert_eq!(constant["raytrace"]["environment"], json!({"color":[0.2,0.4,0.8],"intensity":2.0})); + assert!(h.app.render_workspace.view.raytrace.environment.is_none(), "request building must not mutate the editable base"); + h.app.render_workspace.view.cpu.color[0] = f64::NAN; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.samples = 3; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.samples = 16; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("bad\npath.hdr"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.environment = cpu::Environment::None; + let mut none = json!({}); + cpu::params(&h.app, &mut none).unwrap(); + assert!(none.get("environment").is_none()); + assert!(none["raytrace"].get("environment").is_none()); +} + +#[test] +fn cpu_light_controls_preserve_hidden_spot_fields_and_validate_runtime_bounds() { + use solidcraft_engine::render::job::{DirectionalLightOptions, PunctualLightOptions, SpotConeOptions}; + let mut h = Harness::new(); + h.app.render_workspace.view.raytrace.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + h.app.render_workspace.view.raytrace.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 100.0], + color: [1.0, 0.5, 0.25], + intensity: 4.0, + reference_distance_mm: 100.0, + minimum_distance_mm: 0.01, + cone: None, + }]); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["lights"][0]["intensity"], 2.0); + assert_eq!(params["raytrace"]["punctual_lights"][0]["reference_distance_mm"], 100.0); + assert!(params.get("lighting").is_none(), "CPU must not emit GPU studio lighting"); + h.app.render_workspace.view.raytrace.lights.as_mut().unwrap()[0].direction = [0.0; 3]; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.lights.as_mut().unwrap()[0].direction = [0.0, 0.0, 1.0]; + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].minimum_distance_mm = 101.0; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].minimum_distance_mm = 0.01; + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].cone = + Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.1, outer_half_angle_radians: 0.2 }); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!( + params["raytrace"]["punctual_lights"][0]["cone"], + json!(h.app.render_workspace.view.raytrace.punctual_lights.as_ref().unwrap()[0].cone) + ); +} + +#[test] +fn delayed_cpu_hdr_picker_cannot_write_into_another_document_or_revision() { + use crate::picker_test_support::{Slot, open}; + for other_document in [false, true] { + let mut h = Harness::new(); + let slot: Slot = Default::default(); + open(&mut h.app, &slot); + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "original.hdr".into() }; + hdr::pick(&mut h.app, hdr::Target::Cpu); + let ctx = crate::fonts::test_context(); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(h.app.file_picker_busy()); + if other_document { + h.app.session = Session::default(); + } else { + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5})).unwrap(); + } + *slot.borrow_mut() = Some(Some("late.hdr".into())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.cpu.hdr, hdr::Input::FilePending { path: "original.hdr".into() }); + } +} + +#[test] +fn clicked_setup_save_reload_and_switch_keep_gpu_numeric_intent_without_a_host() { + use solidcraft_engine::doc::render_settings::{GpuJob, RenderJob, SkyEnvironment}; + use solidcraft_engine::render::job::{AreaLight, AreaLights, StudioLighting, Sun, ThinLens, ToneMap}; + use solidcraft_engine::render::lighting::environment::SkyGradient; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.frames(3); + h.app.session.set_render_job_host(None).unwrap(); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + h.app.cam.fov = 0.7; + h.app.ui.perspective = true; + // The positive UI fixture uses the admitted document boundary. Coordinates + // beyond it must still refuse before a setup that cannot reopen is created. + for x in [-2e9, 2e9, 1e9_f64.next_up()] { + assert!( + AreaLights::new(&[AreaLight { center: [x, 0.0, 100.0], u: [2.0, 0.0, 0.0], v: [0.0, -3.0, 0.0], radiance: [3.0, 5.0, 7.0] }]).is_err() + ); + } + let expected = RenderSetup { + camera: h.app.cam, + exposure_ev: 1.25, + width: 48, + height: 32, + job: Some(RenderJob::GpuPath { + transparent_background: true, + options: Box::new(GpuJob { + aging: Default::default(), + nested_media: true, + volume: Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: 0.0, ..Default::default() }), + adaptive: Some(solidcraft_engine::render::job::adaptive::AdaptiveSampling { + pilot_samples: 16, + min_samples: 16, + relative_error: 0.1, + absolute_error: 0.003, + coverage_error: 0.02, + }), + transmission_samples: 4, + finishing: Default::default(), + backdrop: None, + linear_exr: false, + samples: 37, + max_depth: 11, + seed: 1977, + tone_map: ToneMap::AcesFitted, + denoise: true, + lens: Some(ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 123.0 }), + lighting: Some(StudioLighting { + environment: [0.25, 0.5, 0.75], + sun: Some(Sun { direction: [2.0, 3.0, 4.0], angular_radius_rad: 0.0123456789, radiance: [11.0, 22.0, 33.0] }), + area_lights: AreaLights::new(&[AreaLight { + center: [1e9, 0.0, 100.0], + u: [2.0, 0.0, 0.0], + v: [0.0, -3.0, 0.0], + radiance: [3.0, 5.0, 7.0], + }]) + .unwrap(), + }), + environment: Some(SkyEnvironment::Sky { + gradient: SkyGradient { zenith: [0.3, 0.4, 0.5], horizon: [0.6, 0.7, 0.8], ground: [0.1, 0.2, 0.3] }, + rotation_rad: std::f64::consts::PI, + intensity: 1.75, + }), + hdr: None, + }), + }), + ..Default::default() + }; + h.app.run("render.settings.set", json!({"name":"GPU saved","set":expected})).unwrap(); + h.app.render_workspace.view.name = "GPU saved".into(); + setups::load(&mut h.app); + let completed = h.app.render_workspace.view.completed; + let result_camera = h.app.render_workspace.view.result_camera; + h.frames(3); + h.app.run("view.render_select", json!({"kind":"sampling"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + h.app.run("view.render_select", json!({"kind":"light","id":"area:0"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + assert!(image_params(&h.app).is_err(), "offline editing must not claim an executable GPU"); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + h.step(&json!({"click":{"handle":"render:setup-name"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"GPU copy"})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "GPU copy"); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected, "typing Save As must not reset the settings"); + assert!(h.app.render_workspace.view.dirty); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":h.app.tr("render.save_setup")})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.setups["GPU copy"], expected); + h.app.render_workspace.view.seed = 8; + h.app.render_workspace.view.studio.ambient[1] = 0.125; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.step(&json!({"widget":h.app.tr("render.reload_settings")})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + select_image_method(&mut h.app, ImageMethod::Raster); + h.app.render_workspace.view.name = "Raster saved".into(); + setups::save(&mut h.app).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:setups"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:setup:GPU copy"}})).unwrap(); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.completed, completed); + assert_eq!(h.app.render_workspace.view.result_camera, result_camera); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["GPU copy"], expected, "the boundary setup must reopen from JSON"); + let native = solidcraft_engine::io::write_design_container(&h.app.session.doc).unwrap(); + let reopened = solidcraft_engine::io::read_design(&native).unwrap(); + assert_eq!(reopened.render.setups["GPU copy"], expected, "the native container keeps exact numeric intent"); +} + +#[test] +fn cpu_setup_reload_preserves_unedited_numeric_options_and_explicit_empty_values() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2400})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let options: CpuJob = serde_json::from_value(json!({ + "primary_samples":4,"shadows":false, + "lights":[{"direction":[2.0,-4.0,8.0],"color":[0.2,0.4,0.6],"intensity":3.0}], + "punctual_lights":[{"position_mm":[10.0,20.0,30.0],"color":[1.0,0.5,0.25],"intensity":4.0, + "reference_distance_mm":100.0,"minimum_distance_mm":0.01, + "cone":{"emitted_axis":[0.0,0.0,-2.0],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.3}}], + "area_lights":[{"center_mm":[0.0,0.0,100.0],"edge_u_mm":[20.0,0.0,0.0],"edge_v_mm":[0.0,-30.0,0.0],"color":[0.3,0.5,0.7],"intensity":5.0}], + "area_samples":16,"seed":9123,"environment":{"color":[0.0,0.0,0.0],"intensity":2.0} + })) + .unwrap(); + let mut expected = RenderSetup { camera: h.app.cam, exposure_ev: 1.5, job: Some(RenderJob::CpuRaytrace { options }), ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); + h.app.render_workspace.view.name = "CPU numeric".into(); + setups::load(&mut h.app); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + h.app.run("view.render_select", json!({"kind":"light","id":"directional:0"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + assert_eq!(h.app.render_workspace.view.raytrace.exposure_ev, 0.0, "the UI has one exposure authority"); + h.app.render_workspace.view.draft.background = [2, 4, 8]; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + expected.background = [2, 4, 8]; + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(json!(expected)["job"]["options"].get("exposure_ev").is_none()); + for value in [json!({}), json!({"lights":[],"punctual_lights":[],"area_lights":[],"environment":{"color":[0.0,0.0,0.0],"intensity":0.0}})] { + let options: CpuJob = serde_json::from_value(value).unwrap(); + expected.job = Some(RenderJob::CpuRaytrace { options }); + h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + } +} + +#[test] +fn cpu_progressive_controls_resize_only_on_request_and_save_reload_without_a_host() { + use solidcraft_engine::render::job::CpuProgressiveOptions; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.raytrace.primary_samples = 16; + h.app.render_workspace.view.draft.width = 1024; + h.app.render_workspace.view.draft.height = 1024; + h.frames(3); + h.step(&json!({"click":{"handle":"render:cpu-sampling"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-progressive"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 1); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions::default())); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1024, 1024)); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: u32::MAX }); + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.name = "Progressive CPU".into(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(image_request(&h.app).is_err()); + assert!(setups::save(&mut h.app).is_err()); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1024, 1024)); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let resize = format!("{} 512 × 512", h.app.tr("render.image_use_largest")); + assert!(h.widget(&resize).is_some(), "the proposed dimensions must be visible before accepting them"); + h.step(&json!({"widget":resize})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (512, 512)); + let expected = setups::snapshot(&h.app).unwrap(); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + assert!(image_request(&h.app).unwrap().get("progressive").is_none(), "CPU sampling must not select the GPU executor"); + h.step(&json!({"widget":h.app.tr("render.save_setup")})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Progressive CPU"], expected); + h.step(&json!({"click":{"handle":"render:cpu-sampling"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-fixed"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert!(h.app.render_workspace.view.dirty); + h.step(&json!({"widget":h.app.tr("render.reload_settings")})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + h.app.render_workspace.view.name = "Progressive CPU copy".into(); + setups::save(&mut h.app).unwrap(); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.raytrace.exposure_ev, 0.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 1.25); +} + +#[test] +fn cpu_progressive_setup_preserves_hidden_values_empty_lists_and_one_exposure() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; + let mut h = Harness::new(); + h.app.session.set_render_job_host(None).unwrap(); + let options: CpuJob = serde_json::from_value(json!({ + "primary_samples":1,"progressive":{"samples_per_pixel":7,"seed":321},"preset":null, + "lights":[],"punctual_lights":null,"area_lights":[],"area_samples":16,"seed":9123, + "shadows":false,"environment":{"color":[0.0,0.0,0.0],"intensity":0.0} + })) + .unwrap(); + let expected = RenderSetup { + camera: h.app.cam, + width: 32, + height: 16, + exposure_ev: -1.5, + job: Some(RenderJob::CpuRaytrace { options }), + ..Default::default() + }; + h.app.run("render.settings.set", json!({"name":"Progressive hidden","set":expected})).unwrap(); + h.app.render_workspace.view.name = "Progressive hidden".into(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["method"], "gpu_path"); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().seed = 654; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + let undo = h.app.session.undo.len(); + setups::save(&mut h.app).unwrap(); + assert_eq!(h.app.session.undo.len(), undo, "a no-op Save must preserve all nonedited intent"); +} + +#[test] +fn setup_save_refuses_nonportable_state_atomically_and_tracks_invalid_legacy_edits() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Target"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + setups::load(&mut h.app); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + setups::save(&mut h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "must-not-be-read.hdr".into() }; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + assert!(setups::save(&mut h.app).unwrap_err().contains(h.app.tr("render.hdr_inspect_required"))); + h.app.render_workspace.view.studio.environment = studio::Environment::None; + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let binding = materials::Binding::new(target, &h.app); + h.app.render_workspace.view.materials.bindings.push(binding); + h.app.render_workspace.view.materials.enabled = false; + assert!(setups::save(&mut h.app).is_err(), "disabled assignments must not be silently lost either"); + h.app.render_workspace.view.materials.bindings.clear(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + cpu::set_reflection(&mut h.app, "Target", Some(ReflectionMode::Mirror)).unwrap(); + assert!(setups::save(&mut h.app).is_err()); + assert!(h.app.render_workspace.view.raytrace.reflections.is_some()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.run("render.settings.set", json!({"name":"Legacy","set":{"job":null,"environment_rotation":0.25,"environment_intensity":2.0}})).unwrap(); + h.app.render_workspace.view.name = "Legacy".into(); + setups::load(&mut h.app); + assert!(!h.app.render_workspace.view.dirty); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.draft.background = [1, 3, 5]; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty, "invalid saved intent still needs complete dirty tracking"); + assert!(setups::save(&mut h.app).unwrap_err().contains(h.app.tr("render.setup_legacy_environment"))); + assert_eq!(h.app.render_workspace.view.draft.environment_rotation, 0.25); + assert_eq!(h.app.render_workspace.view.draft.environment_intensity, 2.0); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +fn original_hdr_bytes(value: u8, declared_primaries: bool) -> Vec { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n".to_vec(); + if declared_primaries { + bytes.extend_from_slice(b"PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n"); + } + bytes.extend_from_slice(b"\n-Y 1 +X 2\n"); + bytes.extend_from_slice(&[value, 128, 128, 129, 128, value, 128, 129]); + bytes +} + +/// A verified selector for pure request tests. No file exists or is read by the builder. +fn captured_hdr_input(path: &str) -> hdr::Input { + let bytes = original_hdr_bytes(128, true); + hdr::Input::FileCaptured { + path: path.into(), + metadata: hdr::Metadata { + sha256: solidcraft_engine::doc::render_resources::HdrId::of(&bytes), + width: 2, + height: 1, + encoded_bytes: bytes.len() as u64, + primaries: Some(solidcraft_engine::doc::render_resources::SRGB_D65_PRIMARIES), + }, + } +} + +#[test] +fn hdr_ui_save_embeds_once_without_a_host_and_reload_never_reopens_the_source_path() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"HDR target","length":10,"width":20,"height":5})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + let path = h.dir.join("original-embedded.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + let resource = solidcraft_engine::doc::render_resources::HdrId::of(&bytes); + let save = h.app.tr("render.save_setup").to_string(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.render_workspace.view.name = "HDR GPU".into(); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.rotation_rad = 1234.567890123; + h.app.render_workspace.view.studio.intensity = 1.75; + h.app.render_workspace.view.samples = 37; + let before = (h.app.session.revision, h.app.session.undo.len()); + hdr::inspect(&mut h.app, hdr::Target::Gpu, path.to_string_lossy().into_owned()).unwrap(); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), before); + assert!(h.app.session.doc.render.resources.is_empty()); + let unsaved = image_request(&h.app).unwrap(); + assert_eq!(unsaved["environment"]["expected_sha256"], json!(resource)); + h.frames(3); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), before.1 + 1); + assert_eq!(h.app.render_workspace.view.studio.hdr, hdr::Input::EmbeddedResource { resource }); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + let gpu = h.app.session.doc.render.setups.get("HDR GPU").unwrap().clone(); + assert!(matches!(&gpu.job, Some(RenderJob::GpuPath { options, .. }) if options.hdr.unwrap().resource == resource && options.samples == 37)); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":gpu})); + assert!(!h.app.render_workspace.view.dirty); + + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "HDR CPU".into(); + h.app.render_workspace.view.raytrace.progressive = Some(solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: 7, seed: 84 }); + h.app.render_workspace.view.draft.exposure_ev = 1.75; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.rotation_rad = -1234.567890123; + h.app.render_workspace.view.cpu.intensity = 2.5; + h.app.render_workspace.view.cpu.samples = 64; + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let undo = h.app.session.undo.len(); + h.frames(2); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.resources.len(), 1, "both setups share one source payload"); + assert_eq!(h.app.session.doc.render.resources.total_bytes(), bytes.len()); + let cpu = h.app.session.doc.render.setups.get("HDR CPU").unwrap().clone(); + assert!(matches!(&cpu.job, Some(RenderJob::CpuRaytrace { options }) + if options.hdr.unwrap().samples == 64 && options.progressive.unwrap().samples_per_pixel == 7 && options.progressive.unwrap().seed == 84)); + let encoded = h.app.session.doc.to_json(); + assert!(!encoded.contains("original-embedded.hdr"), "the document never stores the source path"); + std::fs::remove_file(&path).unwrap(); + + for (name, expected, target) in [("HDR GPU", gpu, hdr::Target::Gpu), ("HDR CPU", cpu, hdr::Target::Cpu)] { + let loaded = solidcraft_engine::doc::Document::from_json(&encoded).unwrap(); + h.app.session = Session::new(loaded); + h.app.render_workspace.view.name = name.into(); + setups::load(&mut h.app); + let camera = expected.camera; + h.app.cam = camera; + assert_eq!(hdr::input(&h.app, target), &hdr::Input::EmbeddedResource { resource }); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + let before = (h.app.session.revision, h.app.session.undo.len()); + let section = if target == hdr::Target::Cpu { "render.cpu_environment" } else { "render.studio_environment" }; + h.frames(2); + if target == hdr::Target::Gpu { + h.step(&json!({"click":{"handle":format!("dialog:section:{}", h.app.tr("render.image_advanced"))}})).unwrap(); + } + h.step(&json!({"click":{"handle":format!("dialog:section:{}", h.app.tr(section))}})).unwrap(); + h.frames(2); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected, "displaying degrees must preserve saved radians"); + setups::save(&mut h.app).unwrap(); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), before); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn changed_hdr_bytes_reject_save_atomically_and_check_start_keep_the_expected_digest() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "Pinned HDR".into(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + let path = h.dir.join("changing.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let input = h.app.render_workspace.view.cpu.hdr.clone(); + let request = image_request(&h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let draft = h.app.render_workspace.view.draft.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + std::fs::write(&path, original_hdr_bytes(64, true)).unwrap(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), before); + assert_eq!(h.app.render_workspace.view.cpu.hdr, input); + assert_eq!(h.app.render_workspace.view.draft, draft); + assert_eq!(image_request(&h.app).unwrap(), request, "both buttons keep the verified digest, never silently accept new bytes"); + assert!(h.app.session.doc.render.resources.is_empty()); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + assert_ne!(h.app.render_workspace.view.cpu.hdr.resource(), input.resource()); + setups::save(&mut h.app).unwrap(); + assert!(h.app.render_workspace.view.cpu.hdr.embedded()); + assert_eq!(h.app.session.doc.render.resources.len(), 1); +} + +#[test] +fn hdr_picker_cancel_and_late_setup_method_or_input_answers_preserve_the_selection() { + use crate::picker_test_support::{Slot, open}; + for target in [hdr::Target::Cpu, hdr::Target::Gpu] { + for change in ["cancel", "setup", "method", "input"] { + let mut h = Harness::new(); + h.app.render_workspace.view.method = if target == hdr::Target::Cpu { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("original.hdr"); + h.app.render_workspace.view.studio.hdr = captured_hdr_input("original.hdr"); + let slot: Slot = Default::default(); + open(&mut h.app, &slot); + hdr::pick(&mut h.app, target); + let ctx = crate::fonts::test_context(); + crate::file_picker::tick(&mut h.app, &ctx); + match change { + "setup" => h.app.render_workspace.view.name = "another setup".into(), + "method" => h.app.render_workspace.view.method = ImageMethod::Raster, + "input" => { + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("newer.hdr"); + h.app.render_workspace.view.studio.hdr = captured_hdr_input("newer.hdr"); + } + _ => {} + } + let before = hdr::input(&h.app, target).clone(); + let doc = h.app.session.doc.clone(); + let status = h.app.status.clone(); + *slot.borrow_mut() = Some(if change == "cancel" { None } else { Some("never-read-late.hdr".into()) }); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(hdr::input(&h.app, target), &before, "{target:?}: {change}"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.status, status, "the stale path must be discarded before trying to inspect it"); + } + } +} + +#[test] +fn embedded_hdr_runtime_requests_preserve_temporary_bindings_without_serializing_them() { + use solidcraft_engine::render::job::ReflectionMode; + for target in [hdr::Target::Cpu, hdr::Target::Gpu] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"Target","length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, if target == hdr::Target::Cpu { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + let path = h.dir.join("bindings.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + hdr::inspect(&mut h.app, target, path.to_string_lossy().into_owned()).unwrap(); + setups::save(&mut h.app).unwrap(); + let resource = hdr::input(&h.app, target).resource().unwrap(); + std::fs::remove_file(&path).unwrap(); + if target == hdr::Target::Cpu { + cpu::set_reflection(&mut h.app, "Target", Some(ReflectionMode::Mirror)).unwrap(); + } else { + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let binding = materials::Binding::new(target, &h.app); + h.app.render_workspace.view.materials.bindings.push(binding); + // Even disabled, this assignment must not be lost on Save. It still + // selects the runtime path and exercises the embedded HDR selector. + h.app.render_workspace.view.materials.enabled = false; + } + let params = image_request(&h.app).unwrap(); + assert_eq!(params["environment"]["resource"], json!(resource)); + assert!(params["environment"].get("path").is_none()); + assert!(params["environment"].get("expected_sha256").is_none()); + if target == hdr::Target::Cpu { + assert!(params["environment"].get("kind").is_none()); + assert_eq!(params["raytrace"]["reflections"]["bodies"][0]["body"], "Target"); + } else { + assert_eq!(params["environment"]["kind"], "embedded_hdr"); + } + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(image_request(&h.app).unwrap(), params); + } +} + +#[test] +fn cpu_resource_profile_edits_preserve_resolution_samples_and_saved_intent() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "Studio output".into(); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.raytrace.budget = CpuBudget::Studio; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 82 }); + h.frames(3); + let expected = setups::snapshot(&h.app).unwrap(); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + + h.step(&json!({"click":{"handle":"render.cpu_budget_compact"}})).unwrap(); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (3840, 2160)); + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 128); + assert!(setups::snapshot(&h.app).is_err()); + assert!(h.app.render_workspace.view.dirty); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); +} + +#[test] +fn large_image_display_uses_captured_profile_and_keeps_export_pixels_unchanged() { + use solidcraft_engine::render::job::{CpuBudget, ImageRequest, RaytraceOptions}; + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { budget: CpuBudget::Studio, ..Default::default() }), + camera: Camera::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + environment: None, + textures: None, + }; + let limits = captured_image_limits(&request); + assert_eq!(limits, CpuBudget::Studio.image_limits(false)); + assert_eq!(display_dimensions(7680, 4320, 4096).unwrap(), (4096, 2304)); + assert_eq!(display_dimensions(1920, 1080, 4096).unwrap(), (1920, 1080)); + assert!(display_dimensions(u32::MAX, 1, 0).is_err()); + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(8200, 2, image::Rgba([42, 88, 123, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let encoded = png.into_inner(); + let before = encoded.clone(); + assert!(decode_image(&encoded, 8200, 2).is_err(), "legacy default remains compact"); + let display = decode_render_image(&encoded, 8200, 2, CpuBudget::Workstation.image_limits(false), 1024).unwrap(); + assert!(display.size[0] <= 1024 && display.size[1] >= 1); + assert_eq!(encoded, before, "the retained image is not rewritten for its display cache"); + assert!(decode_render_image(&encoded, 8199, 2, CpuBudget::Workstation.image_limits(false), 1024).is_err()); +} + +#[test] +fn setup_actions_and_return_design_stay_visible_with_long_render_controls() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1280,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.frames(3); + for key in ["render.save_setup", "render.reload_settings", "render.return_design"] { + let label = h.app.tr(key).to_string(); + assert!(h.widget(&label).is_some(), "sticky action {key}"); + } + h.step(&json!({"widget":h.app.tr("render.return_design")})).unwrap(); + assert!(!active(&h.app)); +} + +#[test] +fn dirty_indication_preserves_reload_and_resource_picker_hit_targets() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + h.frames(3); + let reload = h.app.tr("render.reload_settings").to_string(); + let clean_reload = h.widget(&reload).unwrap(); + let clean_picker = crate::scenario::rect_of("render:cpu-budget").unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.frames(3); + assert_eq!(h.widget(&reload).unwrap(), clean_reload, "dirty text must not move Reload"); + assert_eq!(crate::scenario::rect_of("render:cpu-budget").unwrap(), clean_picker, "dirty text must not move the CPU resource picker"); + h.step(&json!({"widget":reload})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert!(!h.app.render_workspace.view.dirty); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 0.0); +} + +#[test] +fn product_preview_exact_payload_preserves_mixed_surfaces_and_refuses_overflow() { + let mut session = Session::default(); + for (name, x) in [("Paint", 0), ("Legacy", 20), ("Glass", 40)] { + session.execute("solid.box", &json!({"base":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + } + session + .execute("appearance.assign", &json!({"bodies":["Paint"],"color":"#c07030","pbr":{"metallic":0,"roughness":0.4,"dielectric_ior":1.5}})) + .unwrap(); + session.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.4})).unwrap(); + let original = session.doc.to_json(); + let scene = solidcraft_engine::product_scene::extract(&session).unwrap(); + let plan = preview_upload_plan(&scene, MAX_GEOMETRY_BYTES).unwrap(); + let (_, gpu) = gpu_scene(&scene).unwrap(); + assert_eq!((plan.pbr, plan.tris, plan.glass), (gpu.pbr.len(), gpu.tris.len(), gpu.glass.len())); + assert!(plan.pbr > 0 && plan.tris > 0 && plan.glass > 0); + assert_eq!(plan.source_triangles, scene.meshes.iter().map(|b| b.mesh.triangles.len()).sum::()); + assert!(preview_upload_plan(&scene, plan.bytes().unwrap() - 1).is_err()); + assert!(PreviewUploadPlan::default().add(true, false, usize::MAX, MAX_GEOMETRY_BYTES).is_err()); + assert_eq!(session.doc.to_json(), original); + let mut invalid = scene.clone(); + let source = invalid.meshes[0].mesh.clone(); + Arc::make_mut(&mut invalid.meshes[0].mesh).triangles[0][0] = u32::MAX; + assert!(gpu_scene(&invalid).is_err()); + assert!(gpu_scene(&scene).is_ok()); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &source)); +} + +#[cfg(all(not(target_arch = "wasm32"), target_pointer_width = "64"))] +#[test] +fn full_detail_preview_source_can_exceed_legacy_128_mib_without_mesh_reduction() { + use solidcraft_engine::geom::{Mesh, Vec3}; + use solidcraft_engine::render::{ProductMesh, surface::OpaqueSurface}; + // One immutable original triangle repeated in the index list; this tests + // payload admission only. Actual SELENE upload is separate native evidence. + let count = (128 * 1024 * 1024) / (3 * crate::gpu::PBR_SIZE) + 1; + let mesh = Arc::new(Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]; count], + ..Default::default() + }); + let body = ProductMesh { + name: "Original admission fixture".into(), + mesh: mesh.clone(), + color: [200, 100, 50], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.4, 0.2, 0.1), 0.0, 0.4, 1.5).unwrap()), + transmission: None, + faces: Vec::new(), + }; + let scene = ProductScene { meshes: vec![body], bounds: mesh.bounds() }; + assert!(preview_upload_plan(&scene, 128 * 1024 * 1024).is_err()); + let plan = preview_upload_plan(&scene, MAX_GEOMETRY_BYTES).unwrap(); + assert_eq!(plan.source_triangles, count); + assert_eq!(plan.bytes().unwrap(), count * 3 * crate::gpu::PBR_SIZE); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &mesh)); + let mut maximum = PreviewUploadPlan::default(); + assert!(maximum.add(true, false, MAX_GEOMETRY_BYTES / (3 * crate::gpu::PBR_SIZE) + 1, MAX_GEOMETRY_BYTES).is_err()); +} + +#[test] +fn refused_product_capture_is_cached_until_identity_changes_or_explicit_retry() { + let mut h = Harness::new(); + let calls = std::cell::Cell::new(0); + let signature = (7, 123, 99, MAX_GEOMETRY_BYTES as u64); + for _ in 0..8 { + assert_eq!( + h.app + .render_workspace + .prepare_preview(signature, || { + calls.set(calls.get() + 1); + Err("original bounded refusal".into()) + }) + .unwrap_err(), + "original bounded refusal" + ); + } + assert_eq!(calls.get(), 1, "same refused source is not rebuilt every frame"); + assert!(h.app.render_workspace.scene.is_none() && h.app.render_workspace.key.is_none()); + assert!(h.app.render_workspace.slot.lock().unwrap().is_none()); + assert!( + h.app + .render_workspace + .prepare_preview((8, 123, 99, MAX_GEOMETRY_BYTES as u64), || { + calls.set(calls.get() + 1); + Err("new revision".into()) + }) + .is_err() + ); + assert_eq!(calls.get(), 2); + invalidate_scene(&mut h.app); + assert!(h.app.render_workspace.scene_signature.is_none() && h.app.render_workspace.scene_error.is_none()); + let mut session = Session::default(); + session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap(); + h.app.render_workspace.prepare_preview(signature, || solidcraft_engine::product_scene::extract(&session).map_err(|e| e.to_string())).unwrap(); + assert!(h.app.render_workspace.scene_error.is_none()); + assert!(h.app.render_workspace.preview_upload_bytes.unwrap() > 0); + assert!(h.app.render_workspace.key.is_some() && h.app.render_workspace.scene.is_some()); +} + +#[test] +fn product_preview_error_uses_shared_wrapped_surface_and_explicit_retry_target() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1280,"height":800})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let rect = egui::Rect::from_min_size(egui::pos2(260.0, 200.0), egui::vec2(550.0, 360.0)); + let message = "The original captured product geometry exceeds its bounded preview admission. The renderer must preserve all exact body identities and cannot silently simplify or drop geometry to paint this view."; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0))), ..Default::default() }, + |ui| preview_error(&mut h.app, ui, rect, message), + ); + output.textures_delta.clear(); + let note = crate::scenario::rect_of("dialog:report:render.preview_failure").unwrap(); + let retry = crate::scenario::rect_of("render:preview-retry").unwrap(); + assert!(rect.contains_rect(note) && rect.contains_rect(retry)); + assert!(note.height() > Tokens::get().font_body, "the detailed failure wraps instead of escaping the viewport"); + assert!(crate::theme::contrast_ratio(Tokens::get().form_error, Tokens::get().form_error_fill) >= 3.0); +} + +#[test] +fn finishing_backdrop_and_raw_retention_save_reload_without_a_gpu_or_hidden_transport_edits() { + use solidcraft_engine::render::job::finishing::{Backdrop, BackdropMode, Finishing}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.app.render_workspace.view.name = "Linear studio".into(); + h.app.render_workspace.view.studio.finishing = + Finishing { rgb_gain: [1.3, 0.8, 0.9], saturation: 0.4, contrast: 1.2, vignette: 0.3, ..Default::default() }; + h.app.render_workspace.view.studio.backdrop_enabled = true; + h.app.render_workspace.view.studio.backdrop = Backdrop { mode: BackdropMode::Radial, center: [0.25, 0.7], ..Default::default() }; + h.app.render_workspace.view.studio.linear_exr = true; + let expected = setups::snapshot(&h.app).unwrap(); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.studio = studio::View::default(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + assert!(!studio::linear_export_available(&h.app)); + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["linear_exr"], true); + assert_eq!(request["settings"]["job"]["options"]["finishing"]["rgb_gain"], json!([1.3, 0.8, 0.9])); + assert!(image_params(&h.app).is_err(), "offline editing is not a claim of executable GPU capabilities"); + h.app.render_workspace.view.transparent = true; + assert!(setups::snapshot(&h.app).is_err(), "gradient cannot silently disappear behind alpha mode"); + h.app.render_workspace.view.transparent = false; + let before = h.app.session.doc.to_json(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:post-reset"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.studio.finishing, Finishing::default()); + assert!(h.app.render_workspace.view.studio.linear_exr); + assert!(h.app.render_workspace.view.studio.backdrop_enabled); + assert!(h.app.render_workspace.view.dirty); + assert_ne!(h.app.session.doc.to_json(), before, "Effects saves its job patch through the shared editor"); + let reset = setups::snapshot(&h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), reset); +} + +#[test] +fn missing_linear_master_is_never_reconstructed_from_a_finished_png() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + enter(&mut h.app, true).unwrap(); + let id = completed_preview(&mut h, [21, 37, 55]); + let bytes = h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + h.app.render_workspace.view.completed = Some(id); + h.app.render_workspace.view.studio.export_exr = true; + assert!(!studio::linear_export_available(&h.app)); + let temp = std::env::temp_dir().join(format!("solidcraft-missing-linear-{}.exr", std::process::id())); + assert!(h.app.session.execute("render.export", &json!({"job":id,"path":temp,"format":"exr"})).is_err()); + assert!(!temp.exists()); + assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), bytes); +} + +#[test] +fn render_workspace_stage_commands_keep_registered_actions_without_a_ribbon() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + assert!(crate::workspace::visible_tabs(&h.app).is_empty()); + for command in solidcraft_engine::command_specs() + .into_iter() + .filter(|c| c.id.starts_with("render.") || c.tab.starts_with("RENDER") || c.id == "view.shots_strip") + { + assert!(solidcraft_engine::find_command(command.id).is_some()); + assert!(crate::workspace::destination(command).is_none(), "{} has a ribbon destination", command.id); + } + for tab in ["RENDER", "RENDER APPEARANCE", "RENDER SCENE", "RENDER CAMERA"] { + assert!(crate::workspace::panels(tab).is_empty()); + } + h.frames(3); + assert!(crate::scenario::rect_of("ribbon:card").is_none()); + assert!(crate::scenario::rect_of("tab:RENDER").is_none()); + assert!(crate::scenario::rect_of("render:hud").is_none()); + assert_eq!(h.app.render_workspace.view.stage, Stage::Look); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); +} + +#[test] +fn render_workspace_stage_chips_dispatch_without_mutations_and_remember_each_document() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for stage in Stage::ALL { + h.frames(3); + h.step(&json!({"click":{"handle":format!("render:stage:{}",stage.key())}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.stage, stage); + assert_eq!(h.app.render_workspace.view.inspector.page, stage.page()); + assert_eq!(crate::scenario::rect_of("render:pick").is_some(), stage == Stage::Look); + assert_eq!(crate::scenario::rect_of("render:preview_note").is_some(), stage == Stage::Look); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + // Registered editor navigation remains available independently of the stage. + for command in ["render.status", "render.backends"] { + h.app.start(command); + h.frames(2); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Diagnostics); + } + } + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Look); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + crate::documents::switch(&mut h.app, 0); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Frame); + crate::documents::switch(&mut h.app, 1); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Light); +} + +#[test] +fn render_workspace_stage_shell_degrades_without_overlap_at_small_window_sizes() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.ui.layout = mode; + for (width, height) in [ + (1440, 900), + (1400, 900), + (1100, 700), + (900, 700), + (800, 600), + (700, 600), + (640, 480), + (320, 240), + (240, 160), + (120, 80), + (32, 32), + (1, 1), + ] { + h.call("ui.resize", json!({"width":width,"height":height})); + for stage in Stage::ALL { + h.app.run("view.render_stage", json!({"stage":stage.key()})).unwrap(); + h.frames(3); + let bar = crate::scenario::rect_of("render:stage_bar").unwrap(); + let workspace = crate::scenario::rect_of("ribbon:workspace").unwrap(); + assert!(bar.is_finite() && workspace.is_finite()); + assert_eq!(bar.top(), workspace.top()); + assert_eq!(bar.height(), workspace.height()); + assert!(!bar.intersect(workspace).is_positive()); + if width >= 1100 { + assert_eq!(bar.height(), 88.0); + assert_eq!(workspace.width(), 104.0); + assert_eq!(bar.left() - workspace.right(), 8.0); + let header = crate::scenario::rect_of("render:stage_header").unwrap(); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + assert_eq!(header.height(), 36.0); + assert_eq!(tools.height(), 52.0); + assert_eq!(header.bottom(), tools.top()); + assert_eq!(header.top(), bar.top()); + assert_eq!(tools.bottom(), bar.bottom()); + } + let docks: Vec<_> = + ["render:browser", "render:inspector"].iter().filter_map(|id| h.app.shell.workspace_panels.get(id).map(|(r, _)| *r)).collect(); + if let [browser, inspector] = docks.as_slice() { + assert!((browser.top() - inspector.top()).abs() < 1.0); + assert!(browser.bottom() < inspector.bottom()); + assert!(!browser.intersect(*inspector).is_positive()); + if width >= 800 { + let compact = crate::render_ui::compact(&h.app, width as f32); + assert_eq!(browser.width(), if compact { crate::frame::DIALOG_MIN_W } else { 266.0 }); + assert_eq!(inspector.width(), if compact { crate::frame::DIALOG_MIN_W } else { 305.0 }); + assert_eq!(browser.top() - bar.bottom(), 8.0); + let (strip, _) = h.app.shell.workspace_panels.get("render:shots_strip").unwrap(); + let library = h.app.shell.workspace_panels["render:appearances"].0; + assert_eq!(strip.top() - library.bottom(), 8.0); + assert_eq!(library.top() - browser.bottom(), 8.0); + assert_eq!(strip.height(), 48.0); + } + } + if (640..800).contains(&width) { + assert!(crate::scenario::rect_of("render:browser:show").is_some()); + assert!(!h.app.shell.workspace_panels.contains_key("render:browser")); + } + if width >= 700 { + for dock in &docks { + assert!(!dock.x_range().contains(h.app.viewport.rect.unwrap().center().x), "{width}: {dock:?}"); + } + } + let mut docks = docks; + if let Some((panel, _)) = h.app.shell.workspace_panels.get("render:appearances") { + for dock in &docks { + assert!(!panel.intersect(*dock).is_positive()); + } + docks.push(*panel); + } + for dock in docks { + assert!(!dock.intersect(bar).is_positive(), "{width}×{height}: {dock:?} {bar:?}"); + if let Some((strip, _)) = h.app.shell.workspace_panels.get("render:shots_strip") { + assert!(!dock.intersect(*strip).is_positive(), "{width}×{height}: {dock:?} {strip:?}"); + } + } + } + } + } +} + +#[test] +fn render_workspace_focus_restores_docks_without_design_history_or_camera_changes() { + for (side, folded, shots) in [("left", false, true), ("right", true, false)] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_side = side.into(); + h.app.preferences.render_inspector_side = if side == "left" { "right" } else { "left" }.into(); + h.app.preferences.render_browser_width = 350.0; + h.app.preferences.render_inspector_width = 390.0; + h.app.preferences.render_shots_strip = shots; + h.app.preferences.browser_collapsed = folded; + h.app.shell.render_browser_open = folded; + h.frames(3); + let dock_preferences = h.app.prefs(); + let docks = h.app.shell.workspace_panels.clone(); + let camera = (h.app.cam, h.app.session.camera); + let document = h.app.session.doc.clone(); + let state = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let before = h.app.viewport.layout.as_ref().unwrap().content; + h.app.run("view.render_focus", json!({"on":true})).unwrap(); + h.frames(3); + assert!(crate::render_ui::focused(&h.app)); + crate::shell::register_panel(&mut h.app, "render:stage_panel", Some(before), Some(crate::ui_kit::Edge::Left)); + assert!(!h.app.shell.workspace_panels.contains_key("render:stage_panel")); + for id in ["render:browser", "render:appearances", "render:inspector", "render:shots_strip", "render:shots:show"] { + assert!(!h.app.shell.workspace_panels.contains_key(id)); + assert!(crate::scenario::rect_of(id).is_none()); + } + for id in ["render:focus:exit", "render:stage_bar", "ribbon:workspace"] { + assert!(crate::scenario::rect_of(id).is_some(), "{id}"); + } + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert!(layout.content.width() > before.width()); + assert!(layout.axis_view.is_positive() && layout.navigation.is_positive()); + assert_eq!(h.app.prefs(), dock_preferences); + h.step(&json!({"click":{"handle":"render:focus:exit"}})).unwrap(); + h.frames(3); + assert!(!h.app.shell.render_focus); + assert_eq!(h.app.shell.workspace_panels.len(), docks.len()); + for (id, (rect, edge)) in docks { + let (restored_rect, restored_edge) = h.app.shell.workspace_panels.get(id).unwrap(); + assert_eq!(*restored_rect, rect); + assert_eq!(restored_edge.as_ref().map(std::mem::discriminant), edge.as_ref().map(std::mem::discriminant)); + } + assert_eq!(h.app.prefs(), dock_preferences); + assert_eq!(h.app.preferences.browser_collapsed, folded); + assert_eq!(h.app.shell.render_browser_open, folded); + assert_eq!((h.app.cam, h.app.session.camera), camera); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), state); + assert!(!Harness::new().app.shell.render_focus); + } +} + +#[test] +fn render_workspace_focus_tab_only_toggles_render_without_text_focus() { + let mut h = Harness::new(); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); + enter(&mut h.app, true).unwrap(); + h.frames(3); + h.ctx.memory_mut(|memory| { + if let Some(id) = memory.focused() { + memory.surrender_focus(id); + } + }); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(h.app.shell.render_focus); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); + h.frames(3); + h.step(&json!({"click":{"handle":"render:library-search"}})).unwrap(); + assert!(h.ctx.egui_wants_keyboard_input()); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); +} + +#[test] +fn render_workspace_compact_browser_card_and_focus_preserve_remembered_widths() { + for side in ["left", "right"] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_side = side.into(); + h.app.preferences.render_inspector_side = if side == "left" { "right" } else { "left" }.into(); + h.app.preferences.render_browser_width = 320.0; + h.app.preferences.render_inspector_width = 360.0; + h.frames(3); + for width in [1100, 900, 700] { + h.call("ui.resize", json!({"width":width,"height":700})); + h.frames(3); + if width == 700 { + h.step(&json!({"click":{"handle":"render:browser:show"}})).unwrap(); + h.frames(3); + let (browser, reservation) = h.app.shell.workspace_panels["render:browser"]; + let (inspector, _) = h.app.shell.workspace_panels["render:inspector"]; + assert!(reservation.is_none(), "narrow Browser overlays the canvas"); + assert!(!browser.intersect(inspector).is_positive()); + h.app.run("view.render_focus", json!({"on":true})).unwrap(); + h.frames(3); + h.app.run("view.render_focus", json!({"on":false})).unwrap(); + h.frames(3); + assert!(h.app.shell.render_browser_open); + assert!(h.app.shell.workspace_panels.contains_key("render:browser")); + h.step(&json!({"click":{"handle":"render:browser:hide"}})).unwrap(); + h.frames(3); + assert!(!h.app.shell.workspace_panels.contains_key("render:browser")); + } + assert_eq!(h.app.preferences.render_browser_width, 320.0); + assert_eq!(h.app.preferences.render_inspector_width, 360.0); + } + h.call("ui.resize", json!({"width":1400,"height":900})); + h.frames(3); + assert_eq!(h.app.shell.workspace_panels["render:browser"].0.width(), 320.0); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0.width(), 360.0); + } +} + +#[test] +fn render_workspace_focus_messages_have_five_complete_locales() { + let keys = [ + "cmd.view.render_focus", + "cmd.view.render_browser", + "render.exit_focus", + "render.fold_browser", + "render.spot_cone", + "render.emitted_axis", + "render.inner_half_angle", + "render.outer_half_angle", + "render.layer_off_suffix", + "render.tone_reinhard", + "render.tone_aces_fitted", + "render.size_hd", + "render.size_full_hd", + "render.size_4k_uhd", + "render.result_actual_size", + "render.property_unknown", + "render.property_fallback", + "render.property_source", + "render.property_qualifier", + "render.property_conditions", + "render.property_uncertainty", + "render.error_setup_panicked", + "render.error_setup_worker", + "render.error_setup_stopped", + "render.error_gpu_samples", + "render.error_preview_device", + "render.error_finish_operation", + "render.error_no_completed_image", + "render.error_provisional_identity", + "render.error_checkpoint_dimensions", + "render.error_display_dimensions", + "render.error_display_fit", + "render.error_display_width", + "render.error_display_height", + "render.error_image_profile", + "render.error_decode_budget", + "render.error_image_dimensions", + "render.error_upload_slot", + "render.error_export_document", + "render.error_geometry_size", + "render.error_vertex_envelope", + "render.error_body_bound", + "render.error_triangle_count", + "render.error_triangle_bound", + "render.error_face_cap", + "render.error_opacity", + "render.error_duplicate_face", + "render.error_pbr_opacity", + "render.error_vertex_allocation", + "render.error_product_triangle", + "render.error_surface_normals", + "render.error_vertex_packing", + "render.error_gpu_preview", + "render.error_fixed_preview", + "render.error_finish_gesture", + "render.error_no_scene", + "render.error_no_geometry", + "render.error_visible_solid", + "render.error_area_samples", + "render.error_quality_method", + "render.error_quality_projection", + "render.error_denoise_setting", + "render.error_quality_bounds", + "render.error_library_reply", + "render.error_source_preview", + "render.error_glass_recipe", + "render.error_physical_glass", + "render.error_scene_bodies", + "render.error_scene_body_limit", + "render.error_scene_identity", + "render.error_material_binding", + "render.error_surface_reply", + "render.error_binding_allocation", + "render.error_job_identity", + "render.error_regrade_identity", + "render.error_job_action", + "render.error_interactive_command", + ]; + for (language, source) in [ + ("en", include_str!(concat!(env!("OUT_DIR"), "/locales/en.json"))), + ("ja", include_str!(concat!(env!("OUT_DIR"), "/locales/ja.json"))), + ("zh", include_str!(concat!(env!("OUT_DIR"), "/locales/zh.json"))), + ("de", include_str!(concat!(env!("OUT_DIR"), "/locales/de.json"))), + ("ko", include_str!(concat!(env!("OUT_DIR"), "/locales/ko.json"))), + ] { + let translated: std::collections::BTreeMap = serde_json::from_str(source).unwrap(); + let locale = crate::i18n::Locale::for_language(language); + for key in keys { + let value = translated.get(key).unwrap_or_else(|| panic!("{language}: missing {key}")); + assert!(!value.is_empty()); + assert_eq!(locale.text(key), value); + } + let sentence = locale.format("render.property_source", &[("id", "A"), ("locator", "B")]); + assert!(sentence.contains('A') && sentence.contains('B') && !sentence.contains('{')); + } +} + +#[test] +fn render_workspace_chrome_uses_tokens_instead_of_literal_colours() { + use syn::visit::{self, Visit}; + #[derive(Default)] + struct Colours(Vec); + impl<'ast> Visit<'ast> for Colours { + fn visit_expr_path(&mut self, expr: &'ast syn::ExprPath) { + let names: Vec<_> = expr.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|s| s == "Color32") && names.last().is_some_and(|s| matches!(s.as_str(), "WHITE" | "BLACK" | "GRAY")) { + self.0.push(names.join("::")); + } + visit::visit_expr_path(self, expr); + } + fn visit_expr_call(&mut self, expr: &'ast syn::ExprCall) { + if let syn::Expr::Path(path) = expr.func.as_ref() { + let names: Vec<_> = path.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|s| s == "Color32") + && names.last().is_some_and(|s| s.starts_with("from_rgb") || s == "from_gray") + && expr.args.iter().all(|arg| matches!(arg, syn::Expr::Lit(_))) + { + self.0.push(names.join("::")); + } + } + visit::visit_expr_call(self, expr); + } + } + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files: Vec<_> = std::fs::read_dir(&root) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|path| { + let name = path.file_name().unwrap().to_string_lossy(); + name.starts_with("render_workspace") && name.ends_with(".rs") && !name.contains("tests") + }) + .collect(); + let mut folders = vec![root.join("render_ui")]; + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + folders.push(path); + } else if path.extension().is_some_and(|e| e == "rs") { + files.push(path); + } + } + } + for path in files { + let source = std::fs::read_to_string(&path).unwrap(); + let mut colours = Colours::default(); + colours.visit_file(&syn::parse_file(&source).unwrap()); + assert!(colours.0.is_empty(), "{}: {:?}", path.display(), colours.0); + } +} + +#[test] +fn render_workspace_shots_toggle_persists_and_design_roundtrip_preserves_state() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Subject".into() }]; + h.app.cam.yaw = 0.71; + h.app.cam.pitch = 0.23; + h.app.cam.roll = 0.17; + let camera = h.app.cam; + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let state = ( + h.app.session.undo.len(), + h.app.session.redo.len(), + h.app.session.revision, + h.app.ui.show_timeline, + h.app.preferences.timeline_left, + h.app.preferences.timeline_collapsed, + ); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let strip = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((strip.height() - 48.0).abs() <= 1.0, "{strip:?}"); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + assert!(!h.app.preferences.render_shots_strip); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert_eq!(h.app.session.doc, document); + assert_eq!( + state, + ( + h.app.session.undo.len(), + h.app.session.redo.len(), + h.app.session.revision, + h.app.ui.show_timeline, + h.app.preferences.timeline_left, + h.app.preferences.timeline_collapsed + ) + ); + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:shots_strip").is_none()); + assert!(crate::scenario::rect_of("render:shots:show").is_some()); + h.step(&json!({"click":{"handle":"render:shots:show"}})).unwrap(); + assert!(h.app.preferences.render_shots_strip); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + assert!(!h.app.preferences.render_shots_strip); + let saved = h.app.prefs(); + let mut next = Harness::new(); + next.app.load_prefs(&saved); + assert!(!next.app.preferences.render_shots_strip); + h.frames(2); + h.app.start("view.shots_strip"); + assert!(h.app.preferences.render_shots_strip); + h.frames(3); + assert!(crate::scenario::rect_of("render:shots_strip").is_some()); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), state.0); +} + +#[test] +fn render_workspace_canvas_controls_and_fit_respect_panels_and_shots_in_both_layouts() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.app.run("solid.box", json!({"length":60,"width":40,"height":30})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.cam.fov = 0.9; + h.app.start("render.camera.fit"); + h.frames(4); + assert_eq!(h.app.cam.fov, 0.9); + let free = crate::shell::content_rect(&h.app, h.app.viewport.rect.unwrap()); + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert!(free.contains_rect(layout.navigation), "{free:?} {layout:?}"); + assert!((layout.navigation.center().x - free.center().x).abs() < 1.0); + assert_product_fits_canvas(&h.app); + } +} + +#[test] +fn render_workspace_old_personal_pins_migrate_once_to_task_tabs() { + let mut custom = crate::toolbar_custom::ToolbarCustom::default(); + custom.load(&json!({"version":2,"panels":{ + "DESIGN/RENDER/SCENE":["render.settings.get","render.preset.resolve","solid.box"], + "DESIGN/RENDER/LIGHTING":["render.library.studio.apply"], + "DESIGN/RENDER/CAMERA":["render.settings.apply","render.camera.fit"], + "DESIGN/RENDER/IMAGE":["render.export","render.start"], + "DESIGN/RENDER/OUTPUT":["render.preflight"] + }})); + assert_eq!(custom.panels["DESIGN/RENDER CAMERA/SHOTS"], ["render.settings.get", "solid.box"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STUDIO"], ["render.preset.resolve", "render.library.studio.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER CAMERA/VIEW"], ["render.settings.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER/RESULT"], ["render.export"]); + assert_eq!(custom.panels["DESIGN/RENDER/RENDER"], ["render.start", "render.preflight"]); + let saved = custom.prefs(); + custom.load(&saved); + assert_eq!(custom.prefs(), saved); +} + +#[test] +fn render_workspace_scene_vocabulary_migrates_previous_shell_pins_once() { + let mut custom = crate::toolbar_custom::ToolbarCustom::default(); + custom.load(&json!({"version":2,"panels":{ + "DESIGN/RENDER LIGHTING/LIGHTING":["render.library.studio.apply","render.lights.solo"], + "DESIGN/RENDER LIGHTING/ENVIRONMENT":["render.library.environment.apply","render.hdr.inspect"], + "DESIGN/RENDER/OUTPUT":["render.preflight","render.quality.prepare"], + "DESIGN/RENDER/RESULTS":["render.export","render.effects.describe"] + }})); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STUDIO"], ["render.library.studio.apply", "render.library.environment.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/LIGHTS"], ["render.lights.solo"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STAGE"], ["render.hdr.inspect"]); + assert_eq!(custom.panels["DESIGN/RENDER/IMAGE"], ["render.quality.prepare", "render.effects.describe"]); + assert_eq!(custom.panels["DESIGN/RENDER/RENDER"], ["render.preflight"]); + assert_eq!(custom.panels["DESIGN/RENDER/RESULT"], ["render.export"]); + let saved = custom.prefs(); + custom.load(&saved); + assert_eq!(custom.prefs(), saved); +} + +fn assert_product_fits_canvas(app: &SolveApp) { + let layout = app.viewport.layout.as_ref().unwrap(); + let free = crate::shell::content_rect(app, layout.viewport); + assert!(free.contains_rect(layout.drawable), "fit region {:?} outside canvas {free:?}", layout.drawable); + let bounds = solidcraft_engine::product_scene::extract(&app.session).unwrap().bounds; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + for z in [bounds.min.z, bounds.max.z] { + let (sx, sy, _) = app + .cam + .to_screen( + solidcraft_engine::geom::Vec3::new(x, y, z), + f64::from(layout.viewport.width()), + f64::from(layout.viewport.height()), + bounds.diagonal().max(10.0), + ) + .unwrap(); + let at = layout.viewport.min + egui::vec2(sx as f32, sy as f32); + assert!(layout.drawable.contains(at), "product corner {at:?} outside {:?}", layout.drawable); + } + } + } +} + +#[test] +fn render_workspace_hosts_float_and_shield_input_in_both_ribbon_layouts() { + for (layout, page) in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] + .into_iter() + .flat_map(|layout| [inspector::Page::Scene, inspector::Page::Appearance].map(|page| (layout, page))) + { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.app.run("solid.box", json!({"length":30,"width":20,"height":10})).unwrap(); + h.frames(4); + + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = page; + h.frames(4); + let viewport = h.app.viewport.rect.unwrap(); + let history = crate::timeline::floating_rect(viewport); + let shots = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((shots.height() - 48.0).abs() <= 1.0, "{layout:?}: {shots:?}"); + assert!( + (shots.left() - history.left()).abs() < 1.0 + && (shots.right() - history.right()).abs() < 1.0 + && (shots.bottom() - history.bottom()).abs() < 1.0, + "Shots must reuse History's floating placement: {shots:?} {history:?}" + ); + for key in ["render:inspector", "render:browser", "render:appearances", "render:shots_strip"] { + let (card, _) = h.app.shell.workspace_panels.get(key).unwrap(); + assert!(viewport.contains_rect(*card), "{layout:?} {key}: {card:?} outside {viewport:?}"); + assert!(crate::shell::covered(&h.app, card.center()), "{key} must shield the viewport"); + } + let inspector = h.app.shell.workspace_panels["render:inspector"].0; + let browser = h.app.shell.workspace_panels["render:browser"].0; + let appearances = h.app.shell.workspace_panels["render:appearances"].0; + let ribbon_bottom = h.app.shell.cards.iter().map(|r| r.bottom()).fold(0.0, f32::max); + assert!((browser.top() - inspector.top()).abs() < 1.0); + assert!((appearances.bottom() - inspector.bottom()).abs() < 1.0); + assert!(browser.height() <= 330.0, "Browser must stay within the fixed tree height: {browser:?}"); + for key in ["render:browser", "render:inspector"] { + let card = h.app.shell.workspace_panels[key].0; + assert!( + (card.top() - ribbon_bottom - Tokens::get().space_8).abs() < 1.0, + "{layout:?} {key}: gap {} must be 8 pt", + card.top() - ribbon_bottom + ); + } + for key in ["render:browser", "render:appearances", "render:inspector"] { + let card = h.app.shell.workspace_panels[key].0; + let header = crate::scenario::rect_of(&format!("{key}:header")).unwrap(); + assert!((header.height() - crate::ui_kit::header_height()).abs() < 0.1, "{key}: {header:?}"); + assert!((header.top() - card.top()).abs() <= 1.0, "header must have no outer content padding"); + let control = crate::scenario::rect_of(if key == "render:browser" { + "render:tree:by-look" + } else if key == "render:appearances" { + "render:library-search" + } else if page == inspector::Page::Appearance { + "dialog:editor_footer" + } else { + "render:scene:look" + }) + .unwrap(); + if key == "render:browser" { + assert!(header.contains_rect(control), "Scene lens belongs in the title band"); + } else { + assert!(control.top() >= header.bottom(), "editor controls must be below the standard header: {control:?} {header:?}"); + } + } + + assert!((browser.width() - appearances.width()).abs() < 1.0); + assert!((appearances.top() - browser.bottom() - Tokens::get().space_8).abs() < 1.0); + assert!(appearances.bottom() < shots.top()); + assert!(browser.left() > viewport.left() && inspector.right() < viewport.right()); + assert!(inspector.bottom() < shots.top() && browser.bottom() < shots.top()); + let camera = h.app.cam; + h.step( + &json!({"drag":[[inspector.center().x,inspector.center().y],[inspector.center().x-30.0,inspector.center().y+20.0]],"button":"middle"}), + ) + .unwrap(); + assert_eq!(h.app.cam, camera, "middle dragging over the card must not reach the model"); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.viewport.rect, Some(viewport), "floating strips must preserve the viewport projection"); + let pill = h.app.shell.workspace_panels["render:shots:show"].0; + assert!(crate::shell::covered(&h.app, pill.center())); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert!(h.app.shell.workspace_panels.is_empty(), "Render card reservations must not leak into Design"); + } +} + +#[test] +fn render_workspace_assignment_footer_fits_stacked_card_with_shots_shown_and_hidden() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + for shown in [true, false] { + h.app.run("view.shots_strip", json!({"visible":shown})).unwrap(); + h.frames(4); + let browser = h.app.shell.workspace_panels["render:browser"].0; + let appearances = h.app.shell.workspace_panels["render:appearances"].0; + // Assignment help is the shared footer's tooltip; its visible anchor stays in the card. + let footer = crate::scenario::rect_of("catalog:footer").unwrap(); + assert!(appearances.contains_rect(footer), "{layout:?}, Shots {shown}: footer {footer:?} outside {appearances:?}"); + let gap = Tokens::get().space_8; + assert!((appearances.top() - browser.bottom() - gap).abs() < 1.0); + let bounds = crate::shell::panel_bounds(&h.app, h.app.viewport.rect.unwrap()); + assert!((bounds.bottom() - appearances.bottom() - gap).abs() < 1.0, "{layout:?}, Shots {shown}: {appearances:?}, {bounds:?}"); + } + } +} + +#[test] +fn render_workspace_card_grips_swap_sides_and_resize_without_design_edits() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + h.step(&json!({"drag":[{"handle":"render:inspector:grip"},[100.0,350.0]],"steps":8})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_inspector_side, "left"); + assert_eq!(h.app.preferences.render_browser_side, "right"); + assert!(h.app.shell.workspace_panels["render:inspector"].0.right() < h.app.shell.workspace_panels["render:browser"].0.left()); + let width = h.app.preferences.render_inspector_width; + let card_width = h.app.shell.workspace_panels["render:inspector"].0.width(); + let rail = crate::scenario::handle_at("render:inspector:resize").unwrap(); + h.step(&json!({"drag":[[rail.x,rail.y],[rail.x+50.0,rail.y]],"steps":8})).unwrap(); + h.frames(3); + // A compact dock keeps its minimum width and leaves the remembered width alone. + if layout == crate::shell::LayoutMode::Docked { + assert_eq!(h.app.preferences.render_inspector_width, width); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0.width(), card_width); + } else { + assert!(h.app.preferences.render_inspector_width > width); + assert!(h.app.shell.workspace_panels["render:inspector"].0.width() > card_width); + } + h.step(&json!({"click":{"handle":"render:tree:by-look"}})).unwrap(); + h.frames(3); + h.step(&json!({"drag":[{"handle":"render:browser:grip"},[100.0,350.0]],"steps":8})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_browser_side, "left"); + assert_eq!(h.app.preferences.render_inspector_side, "right"); + assert!(h.app.shell.workspace_panels["render:browser"].0.right() < h.app.shell.workspace_panels["render:inspector"].0.left()); + assert_eq!(h.app.cam, camera, "card gestures must not move the camera"); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + } +} + +/// A small public-safe model, built through the sample recipe inside an occurrence. +fn render_pick_sample() -> (Harness, u64) { + let mut h = Harness::new(); + let part = h.app.run("component.create", json!({"name":"Sample","grounded":false})).unwrap(); + let occurrence = part["occurrence"].as_u64().unwrap(); + h.app.session.run_script(&solidcraft_engine::sample::script()).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.start("render.camera.fit"); + h.settle(); + (h, occurrence) +} + +fn product_pick_point(h: &Harness) -> egui::Pos2 { + let rect = h.app.viewport.layout.as_ref().unwrap().drawable; + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + for y in 2..18 { + for x in 2..18 { + let at = rect.min + egui::vec2(rect.width() * x as f32 / 20.0, rect.height() * y as f32 / 20.0); + if !crate::shell::covered(&h.app, at) + && crate::viewport::pick(&h.app, &proj, at).iter().any(|h| matches!(h, crate::viewport::Hit::Face { .. })) + { + return at; + } + } + } + panic!("sample must offer a visible product face outside the floating panels"); +} + +#[test] +fn render_workspace_pick_stage_tools_filter_sample_clicks_with_shots_shown_and_hidden() { + use solidcraft_engine::Sel; + let (mut h, occurrence) = render_pick_sample(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for shots in [true, false] { + h.app.run("view.shots_strip", json!({"visible":shots})).unwrap(); + h.frames(3); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + assert!(tools.contains_rect(crate::scenario::rect_of("render:pick").unwrap())); + assert!(tools.contains_rect(crate::scenario::rect_of("render:preview_note").unwrap())); + assert!(crate::scenario::rect_of("render:hud").is_none()); + for mode in ["body", "face", "component"] { + assert!(crate::scenario::handle_at(&format!("render:pick:{mode}")).is_some(), "Pick must be enabled"); + h.step(&json!({"click":{"handle":format!("render:pick:{mode}")}})).unwrap(); + h.frames(2); + let at = product_pick_point(&h); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + assert!(matches!(h.app.viewport.hover, Some(crate::viewport::Hit::Face { .. }))); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + match h.app.session.selection.as_slice() { + [Sel::Body { name }] if mode == "body" => assert_eq!(name, "Plate"), + [Sel::Face { body, .. }] if mode == "face" => assert_eq!(body, "Plate"), + [Sel::Occurrence { path }] if mode == "component" => assert_eq!(path, &[occurrence]), + other => panic!("{mode}, Shots {shots}: wrong selection {other:?}"), + } + let selected = h.app.session.selection.clone(); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert_eq!(h.app.session.selection, selected); + enter(&mut h.app, true).unwrap(); + h.settle(); + assert_eq!(h.app.session.selection, selected); + } + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.tool.is_none() && h.app.dialog.is_none()); +} + +#[test] +fn render_workspace_click_modifiers_clear_and_browser_share_selection() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + for (name, x) in [("Left", -30), ("Right", 30)] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":20,"width":20,"height":20,"body_name":name})).unwrap(); + } + enter(&mut h.app, true).unwrap(); + h.settle(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let left = proj.to_screen(solidcraft_engine::geom::Vec3::new(-20.0, 10.0, 20.0)).unwrap(); + let right = proj.to_screen(solidcraft_engine::geom::Vec3::new(40.0, 10.0, 20.0)).unwrap(); + h.step(&json!({"click":[left.x,left.y]})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Left".into() }]); + h.step(&json!({"click":[right.x,right.y],"shift":true})).unwrap(); + assert_eq!(h.app.session.selection.len(), 2); + h.step(&json!({"click":[left.x,left.y],"ctrl":true})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Right".into() }]); + h.app.preferences.selection_shift_add_only = true; + h.step(&json!({"click":[right.x,right.y],"shift":true})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Right".into() }]); + // A Browser body row writes the same selection and immediately feeds the product overlay. + h.step(&json!({"click":{"handle":"row:Left"}})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Left".into() }]); + assert!(!crate::viewport::build_highlight(&h.app).merged().tris.is_empty()); + let empty = h.app.viewport.layout.as_ref().unwrap().drawable.left_bottom() + egui::vec2(10.0, -10.0); + h.step(&json!({"click":[empty.x,empty.y]})).unwrap(); + assert!(h.app.session.selection.is_empty()); + assert!(h.app.viewport.hover.is_none()); +} + +#[test] +fn render_workspace_selection_overlay_never_changes_started_frames_png_or_retained_results() { + use solidcraft_engine::Sel; + let (mut h, _) = render_pick_sample(); + let at = product_pick_point(&h); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let hit = crate::viewport::pick(&h.app, &proj, at).into_iter().next().unwrap(); + let face = crate::viewport::hit_sel(&hit).unwrap(); + let first = completed_preview(&mut h, [230, 230, 230]); + let clean = h.app.session.render_job_handle(first).unwrap().frame().unwrap().unwrap(); + let clean_scene = gpu_scene(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap()).unwrap(); + h.app.run("select.set", json!({"items":[face]})).unwrap(); + let face_overlay = crate::viewport::build_highlight(&h.app).merged(); + assert!(!face_overlay.tris.is_empty()); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Plate".into() }]})).unwrap(); + let body_overlay = crate::viewport::build_highlight(&h.app).merged(); + assert!(body_overlay.tris.len() > face_overlay.tris.len(), "Face must only tint the selected face"); + h.app.viewport.hover = Some(hit); + let second = completed_preview(&mut h, [230, 230, 230]); + let selected = h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap(); + assert_eq!(clean.png(), selected.png(), "started image job must never capture selection or hover pixels"); + let after = gpu_scene(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap()).unwrap(); + assert_eq!(clean_scene.0, after.0); + assert_eq!(clean_scene.1.tris, after.1.tris); + h.app.render_workspace.view.completed = Some(second); + h.app.render_workspace.view.result = true; + h.frames(3); + h.app.run("select.filter", json!({"mode":"face"})).unwrap(); + h.step(&json!({"click":{"handle":"render:pick:body"}})).unwrap(); + assert!(!h.app.ui.pick_bodies && !h.app.ui.pick_components, "result canvas must disable the stage's Pick control"); + let path = h.dir.join("overlay-free.png"); + h.app.run("render.export", json!({"job":second,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), clean.png()); + assert_eq!(h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap().png(), clean.png()); +} + +#[test] +fn render_workspace_pick_filter_rejects_invalid_requests_atomically() { + let mut h = Harness::new(); + let doc = h.app.session.doc.clone(); + for mode in ["body", "face", "component"] { + assert_eq!(h.app.run("select.filter", json!({"mode":mode})).unwrap()["mode"], mode); + assert_eq!(h.app.ui.pick_bodies, mode == "body"); + assert_eq!(h.app.ui.pick_components, mode == "component"); + } + for request in [json!({}), json!({"mode":"edge"}), json!({"mode":"body","extra":true})] { + assert!(h.app.run("select.filter", request).is_err()); + assert!(!h.app.ui.pick_bodies && h.app.ui.pick_components); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(h.app.session.undo.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_workspace_product_pass_draws_only_requested_face_or_body_overlay() { + let mut app = nav_app(true, "fusion", crate::prefs::OrbitAround::ViewCentre); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(256.0, 256.0)); + app.viewport.rect = Some(rect); + let proj = crate::viewport::projection(&app, rect); + let hit = crate::viewport::pick(&app, &proj, rect.center()).into_iter().find(|h| matches!(h, crate::viewport::Hit::Face { .. })).unwrap(); + let face = crate::viewport::hit_sel(&hit).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&app.session).unwrap(); + let gpu = gpu_scene(&scene).unwrap().1; + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(app.cam.target); + let eye = app.cam.eye().to_f32(); + let camera = app.cam; + let draw = |overlay| { + crate::gpu::render_product_offscreen( + gpu.clone(), + overlay, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], 1.0], + 256, + false, + ) + }; + let Some(clean) = draw(None) else { + eprintln!("skipping: no GPU adapter for product overlay pixels"); + return; + }; + app.run("select.set", json!({"items":[face]})).unwrap(); + let face_pixels = draw(Some(crate::viewport::build_highlight(&app))).unwrap(); + app.run("select.set", json!({"items":[{"type":"body","name":"Product"}]})).unwrap(); + let body_pixels = draw(Some(crate::viewport::build_highlight(&app))).unwrap(); + let changed = |image: &[u8]| clean.as_chunks::<4>().0.iter().zip(image.as_chunks::<4>().0).filter(|(a, b)| a != b).count(); + assert!(changed(&face_pixels) > 100, "Face overlay must reach the product pass"); + assert!(changed(&body_pixels) > changed(&face_pixels) + 100, "Face must leave the other faces untouched"); +} + +#[test] +fn render_workspace_pick_projection_matches_orthographic_and_custom_perspective_camera() { + use egui::{Event, Modifiers, PointerButton}; + use solidcraft_engine::geom::Vec3; + for fov in [0.0, 0.6, 1.1] { + let mut app = nav_app(true, "fusion", crate::prefs::OrbitAround::ViewCentre); + app.cam.fov = fov; + let ctx = crate::fonts::test_context(); + let mut time = 0.0; + nav_frame(&mut app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + let rect = app.viewport.rect.unwrap(); + let proj = crate::viewport::projection(&app, rect); + assert_eq!(proj.cam.fov, fov); + let (x, y, _) = app.cam.to_screen(Vec3::new(20.0, 15.0, 20.0), f64::from(rect.width()), f64::from(rect.height()), 100.0).unwrap(); + let pos = rect.min + egui::vec2(x as f32, y as f32); + nav_frame(&mut app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(pos)]); + assert!(matches!(app.viewport.hover, Some(crate::viewport::Hit::Face { .. })), "FOV {fov}"); + for pressed in [true, false] { + nav_frame( + &mut app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], + ); + } + assert!(matches!(app.session.selection.as_slice(), [solidcraft_engine::Sel::Face { body, .. }] if body == "Product"), "FOV {fov}"); + } +} + +#[test] +fn render_workspace_component_filter_keeps_nested_repeated_occurrences_distinct() { + use crate::viewport::{Hit, candidate}; + use solidcraft_engine::{Sel, geom::Vec3}; + let mut h = Harness::new(); + let parent = h.app.run("component.create", json!({"name":"Parent"})).unwrap(); + let child = h.app.run("component.create", json!({"name":"Part"})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Solid"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let second = h.app.run("occurrence.copy", json!({"occurrence":parent["occurrence"],"translate":[50,0,0]})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.filter", json!({"mode":"component"})).unwrap(); + for top in [parent["occurrence"].as_u64().unwrap(), second["occurrence"].as_u64().unwrap()] { + let path = vec![top, child["occurrence"].as_u64().unwrap()]; + let names = h.app.session.occurrence_bodies(&path, true).unwrap(); + assert_eq!(names.len(), 1); + let hit = Hit::Face { body: names[0].clone(), index: 0, point: Vec3::ZERO }; + assert_eq!(candidate(&h.app, &[hit]).unwrap().1, Sel::Occurrence { path }); + } +} + +#[test] +fn navigation_bar_render_canvases_filter_slots_and_keep_product_fit() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.preferences.look_at_anim = false; + h.settle(); + assert_eq!(crate::navigation_bar::canvas_caps(&h.app), crate::navigation::NavCaps::RENDER); + // The product preview picks (#6426), so the slots that need a pick are on the bar there too. + for slot in ["orbit", "pan", "zoom", "fit", "look_at", "home", "visual_style", "display"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_some(), "{slot}"); + } + h.app.cam.pan(100.0, 50.0, 600.0); + let panned = h.app.cam; + h.step(&json!({"click":{"handle":"nav:slot:fit"}})).unwrap(); + assert_ne!(h.app.cam.target, panned.target, "Fit recentres the product"); + assert_product_fits_canvas(&h.app); + let mut iso = h.app.cam; + iso.set_view(solidcraft_engine::render::StandardView::Iso); + h.app.cam.orbit(0.4, 0.2); + h.step(&json!({"click":{"handle":"nav:slot:home"}})).unwrap(); + assert_eq!((h.app.cam.yaw, h.app.cam.pitch), (iso.yaw, iso.pitch), "Home returns to the isometric view"); + assert_product_fits_canvas(&h.app); + + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.result = true; + h.settle(); + assert_eq!(crate::navigation_bar::canvas_caps(&h.app), crate::navigation::NavCaps { orbit: false, pick: false }); + for slot in ["orbit", "look_at", "visual_style"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_none(), "{slot}"); + } + for slot in ["pan", "zoom", "fit", "home", "display"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_some(), "{slot}"); + } +} + +#[test] +fn render_lights_browser_sections_and_lights_describe_current_job_entries() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1100})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let rows: Vec<_> = crate::browser::drawn_rows().into_iter().map(|r| r.0).collect(); + for section in ["Environment", "Lights", "Shots", "Objects"] { + assert!(rows.iter().any(|label| label == section), "{section}: {rows:?}"); + } + assert_eq!(scene::light_types(&h.app), vec!["render.tree_directional"; 3]); + assert_eq!(scene::environment(&h.app).0, "Fixed studio"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace = serde_json::from_value(json!({ + "lights":[{"direction":[0,0,-1],"color":[1,1,1],"intensity":1}], + "punctual_lights":[ + {"position_mm":[0,0,10],"color":[1,1,1],"intensity":1,"reference_distance_mm":10,"minimum_distance_mm":0.1}, + {"position_mm":[0,0,10],"color":[1,1,1],"intensity":1,"reference_distance_mm":10,"minimum_distance_mm":0.1, + "cone":{"emitted_axis":[0,0,-1],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.2}} + ], + "area_lights":[{"center_mm":[0,0,10],"edge_u_mm":[1,0,0],"edge_v_mm":[0,-1,0],"color":[1,1,1],"intensity":1}] + })) + .unwrap(); + assert_eq!(scene::light_types(&h.app), ["render.tree_directional", "render.tree_point", "render.tree_spot", "render.tree_rectangle"]); + h.app.render_workspace.view.raytrace.lights = Some(vec![]); + h.app.render_workspace.view.raytrace.punctual_lights = None; + h.app.render_workspace.view.raytrace.area_lights = None; + assert!(scene::light_types(&h.app).is_empty(), "empty explicit rig must stay empty"); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let studio = &mut h.app.render_workspace.view.studio; + studio.sun_enabled = true; + assert_eq!(scene::light_types(&h.app), vec!["render.tree_directional"; 3], "implicit studio sources are listed"); + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app + .render_workspace + .view + .studio + .area_lights + .push(serde_json::from_value(json!({"center":[0,0,10],"u":[1,0,0],"v":[0,-1,0],"radiance":[1,1,1]})).unwrap()); + assert_eq!(scene::light_types(&h.app), ["render.tree_sun", "render.tree_rectangle"]); + h.app.render_workspace.view.studio.environment = studio::Environment::Sky; + h.app.render_workspace.view.studio.rotation_rad = std::f64::consts::FRAC_PI_2; + h.app.render_workspace.view.studio.intensity = 2.5; + assert_eq!(scene::environment(&h.app), ("Sky".into(), "90° · 2.50×".into())); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:environment:current"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Environment); + h.step(&json!({"click":{"browser":"Key"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); +} + +#[test] +fn render_workspace_browser_look_lens_counts_distinct_objects_and_selects_them() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + for (name, x) in [("A", 0), ("B", 20), ("C", 40)] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + } + h.app.run("appearance.assign", json!({"bodies":["A","B"],"appearance":"ABS - Red"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["C"],"appearance":"ABS - Blue"})).unwrap(); + // Two faces on C use the same look as A and B: still only one additional user. + h.app.run("appearance.assign", json!({"body":"C","faces":[[40,5,5],[45,0,5]],"appearance":"ABS - Red"})).unwrap(); + enter(&mut h.app, true).unwrap(); + let groups = scene::groups(&h.app); + let red = groups.iter().position(|g| g.look.as_ref().is_some_and(|l| l.name == "ABS - Red")).unwrap(); + assert_eq!(groups[red].objects, ["A", "B", "C"]); + assert_eq!(groups.len(), 2); + h.app.render_workspace.view.by_look = true; + // Keep the object rows inside the ten-row Browser viewport while testing their hover. + crate::browser::toggle(&mut h.app, "render:tree:lights", true); + h.frames(3); + let at = crate::scenario::handle_at("row:A").unwrap(); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + h.frames(2); + assert_eq!(h.app.viewport.hover_bodies, ["A"], "By look rows retain Browser hover outlines"); + h.step(&json!({"move":[1000.0,800.0]})).unwrap(); + h.frames(2); + assert!(h.app.viewport.hover_bodies.is_empty(), "leaving the row clears its hover outline"); + h.step(&json!({"click":{"handle":format!("render:tree:look:{red}")}})).unwrap(); + assert_eq!(h.app.session.selection.len(), 3); + for name in ["A", "B", "C"] { + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: name.into() })); + } + h.step(&json!({"click":{"handle":"eye:A"}})).unwrap(); + assert!(h.app.session.visibility.hidden_bodies.contains(&"A".into())); + let menu = crate::context_menu::items(&h.app, &crate::context_menu::Target::Body { name: "A".into() }); + for id in ["select.set", "select.same_look", "ui.isolate", "ui.show"] { + assert!(menu.iter().any(|i| i.id == id)); + } +} + +#[test] +fn render_workspace_dock_command_swaps_sides_without_design_edits() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + let product_camera = h.app.render_workspace.view.draft.camera; + let widths = (h.app.preferences.render_browser_width, h.app.preferences.render_inspector_width); + assert!(crate::shortcut_box::search(&h.app, "view.render_dock").iter().any(|row| row.0 == "view.render_dock")); + for (panel, side, inspector, browser) in [ + ("inspector", "left", "left", "right"), + ("browser", "left", "right", "left"), + ("inspector", "right", "right", "left"), + ("browser", "right", "left", "right"), + ] { + h.app.run("view.render_dock", json!({"panel":panel,"side":side})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_inspector_side, inspector); + assert_eq!(h.app.preferences.render_browser_side, browser); + let a = h.app.shell.workspace_panels["render:inspector"].0; + let b = h.app.shell.workspace_panels["render:browser"].0; + assert_eq!(a.center().x < b.center().x, inspector == "left"); + let view = h.app.viewport.layout.as_ref().unwrap(); + assert!(view.content.contains_rect(view.axis_view)); + let edge = if inspector == "left" { view.axis_view.left() - view.content.left() } else { view.content.right() - view.axis_view.right() }; + assert!(edge.abs() < 0.1); + assert!(!view.navigation.intersects(a)); + assert!(!view.navigation.intersects(b)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.draft.camera, product_camera); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + assert_eq!((h.app.preferences.render_browser_width, h.app.preferences.render_inspector_width), widths); + } + } +} + +#[test] +fn render_workspace_dock_grip_menus_dispatch_the_other_side() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + for panel in ["inspector", "inspector", "browser", "browser"] { + let before = h.app.preferences.render_inspector_side.clone(); + let at = crate::scenario::handle_at(&format!("render:{panel}:grip")).unwrap(); + for pressed in [true, false] { + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }, + ]); + } + h.frames(2); + // Opening the menu must not move either panel. + assert_eq!(h.app.preferences.render_inspector_side, before); + h.step(&json!({"click":{"handle":format!("render:{panel}:move_side")}})).unwrap(); + h.frames(3); + assert_ne!(h.app.preferences.render_inspector_side, before); + assert_ne!(h.app.preferences.render_inspector_side, h.app.preferences.render_browser_side); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + } + } +} + +#[test] +fn render_workspace_browser_shot_switch_keeps_the_existing_dirty_confirmation() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1100})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.name = "A".into(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{"width":321,"job":{"method":"raster"}}})).unwrap(); + h.app.render_workspace.view.draft.width = 123; + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:shot:B"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "A"); + assert!(inspector::confirmation_open(&h.app)); + h.step(&json!({"widget":h.app.tr("render.keep_editing")})).unwrap(); + assert_eq!(h.app.render_workspace.view.draft.width, 123); + h.step(&json!({"click":{"handle":"render:tree:shot:B"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "B"); + assert_eq!(h.app.render_workspace.view.draft.width, 321); + assert!(!h.app.render_workspace.view.dirty); +} + +#[test] +fn render_lights_browser_focus_covers_each_kind_without_design_edits() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Object"})).unwrap(); + h.app.run("render.settings.set", json!({"name":"Shot","set":{"job":{"method":"raster"}}})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.sun_enabled = true; + h.frames(3); + let doc = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + for label in ["Environment", "Lights", "Shots", "Objects", "Output"] { + assert!(crate::browser::drawn_rows().iter().any(|r| r.0 == label), "{label}"); + } + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.step(&json!({"click":{"handle":"row:Object"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Object(vec![Sel::Body { name: "Object".into() }])); + h.step(&json!({"click":{"handle":"render:tree:environment"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Environment); + assert!(crate::scenario::rect_of("dialog:section:Source").is_some()); + assert!(h.app.session.selection.is_empty()); + let focused_revision = h.app.session.revision; + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + assert!(matches!(&h.app.render_workspace.view.selection, RenderSelection::Light(id) if id=="directional:0")); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:shot:Shot"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Shot("Shot".into())); + // The browser is height-capped even in a tall window. Output is its last row, + // and published targets can lie below the scroll clip as more rows are added. + let browser = crate::scenario::rect_of("browser:card").unwrap(); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + h.call("ui.scroll", json!({"x":browser.center().x,"y":(header.bottom()+browser.bottom())/2.0,"delta":-2000})); + h.frames(20); + let browser = crate::scenario::rect_of("browser:card").unwrap(); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + let output = crate::scenario::handle_at("render:tree:output").unwrap(); + assert!( + browser.shrink(Tokens::get().space_8).contains(output) && output.y > header.bottom(), + "Output click must be inside the visible browser body" + ); + h.step(&json!({"click":{"handle":"render:tree:output"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); + assert_eq!(h.app.session.revision, focused_revision, "semantic selection only refreshes the view when clearing object picks"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +#[test] +fn render_lights_browser_eye_and_solo_are_view_state_and_editor_opening_is_read_only() { + let mut h = render_lights_fixture(); + h.frames(3); + assert!(crate::browser::drawn_rows().iter().any(|row| row.0 == "Key")); + assert!(crate::browser::drawn_rows().iter().any(|row| row.0 == "Fill")); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.step(&json!({"click":{"handle":"eye:Key"}})).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + h.step(&json!({"click":{"handle":"render:tree:light:1:solo"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.lights.visibility.solo.as_deref(), Some("directional:1")); + h.step(&json!({"click":{"handle":"render:tree:light:1"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + assert!(crate::scenario::handle_at("render:tree:shots:add").is_some()); + h.step(&json!({"click":{"handle":"render:tree:shots:add"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); +} + +#[test] +fn render_workspace_browser_stage_expansion_never_locks_rows_or_changes_focus() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + let doc = h.app.session.doc.clone(); + let sections = ["objects", "lights", "environment", "shots"]; + for (stage, expanded) in [("look", vec!["objects"]), ("light", vec!["lights", "environment"]), ("frame", vec!["shots"]), ("output", vec![])] { + for section in sections { + h.app.tree.collapsed.insert(format!("render:tree:{section}")); + } + h.app.run("view.render_stage", json!({"stage":stage})).unwrap(); + for section in sections { + assert_eq!(crate::browser::is_open(&h.app, &format!("render:tree:{section}"), true), expanded.contains(§ion), "{stage}/{section}"); + crate::browser::toggle(&mut h.app, &format!("render:tree:{section}"), true); + assert_eq!(crate::browser::is_open(&h.app, &format!("render:tree:{section}"), true), !expanded.contains(§ion)); + } + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); +} + +#[test] +fn render_workspace_browser_semantic_focus_survives_clearing_object_picks() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Object"})).unwrap(); + enter(&mut h.app, true).unwrap(); + let doc = h.app.session.doc.clone(); + let evaluated = h.app.session.world_state(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + for (request, expected) in [ + (json!({"kind":"environment"}), RenderSelection::Environment), + (json!({"kind":"lighting"}), RenderSelection::Lighting), + (json!({"kind":"light","id":"sun"}), RenderSelection::Light("sun".into())), + (json!({"kind":"shot","id":"Shot"}), RenderSelection::Shot("Shot".into())), + (json!({"kind":"output"}), RenderSelection::Output), + (json!({"kind":"nothing"}), RenderSelection::Nothing), + ] { + h.app.run("select.set", json!({"items":[Sel::Body { name:"Object".into() }]})).unwrap(); + assert!(matches!(h.app.render_workspace.view.selection, RenderSelection::Object(_))); + h.app.run("view.render_select", request.clone()).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.selection, expected, "{request}"); + assert!(h.app.session.selection.is_empty()); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(Arc::ptr_eq(&evaluated, &h.app.session.world_state())); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); +} + +#[test] +fn render_workspace_browser_focus_is_per_document_and_invalid_selection_is_atomic() { + let mut h = Harness::new(); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + let doc = h.app.session.doc.clone(); + for request in [ + json!({}), + json!({"kind":"object"}), + json!({"kind":"light"}), + json!({"kind":"shot","id":""}), + json!({"kind":"lighting","id":"extra"}), + json!({"kind":"output","id":"x"}), + json!({"kind":"shot","id":"x".repeat(1025)}), + json!({"kind":"nothing","extra":1}), + ] { + assert!(h.app.run("view.render_select", request).is_err()); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + crate::documents::switch(&mut h.app, 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); +} + +#[test] +fn render_workspace_wear_tree_selects_the_scene_stack_and_counts_layers_in_both_lenses() { + use solidcraft_engine::render::job::aging::{AgingKind, AgingLayer}; + fn has_text(shape: &egui::Shape, needle: &str) -> bool { + match shape { + egui::Shape::Text(text) => text.galley.text().contains(needle), + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| has_text(shape, needle)), + _ => false, + } + } + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body { name: "Subject".into() }]})).unwrap(); + let document = h.app.session.doc.clone(); + assert_eq!(scene::wear_subtitle(&h.app), h.app.tr("render.wear_no_layers")); + h.frames(3); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, h.app.tr("render.wear_no_layers")))); + h.step(&json!({"click":{"handle":"render:tree:wear"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Wear); + assert!(h.app.session.selection.is_empty()); + assert!(crate::scenario::rect_of("render:wear:controls").is_some()); + assert!(!crate::icon_svg::resolve("appearance").placeholder); + for count in 1..=2 { + h.app.render_workspace.view.studio.aging.push(AgingLayer::preset(AgingKind::Dust)).unwrap(); + h.app.render_workspace.view.dirty = true; + let label = + crate::i18n::format(if count == 1 { "render.wear_layer_one" } else { "render.wear_layer_count" }, &[("count", &count.to_string())]); + assert_eq!(scene::wear_subtitle(&h.app), label); + for by_look in [false, true] { + h.app.run("view.render_browser", json!({"by_look":by_look})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:tree:wear").is_some()); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, &label))); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +/// Actual application tree at the approved card width, in both themes and both task states. +#[test] +fn render_workspace_browser_compact_geometry_search_and_theme_evidence() { + let previous = crate::theme::is_dark(); + let mut themes = Vec::new(); + for dark in [false, true] { + let mut h = Harness::new(); + for (name, x, appearance) in [ + ("Plate", 0, "Aluminum - Satin"), + ("Boss", 20, "Aluminum - Anodized Blue"), + ("Knob", 40, "Copper"), + ("Cover", 60, "Glass - Clear"), + ("Spacer", 80, "Aluminum - Satin"), + ("Bolt", 100, "Aluminum - Satin"), + ("Nut", 120, "Aluminum - Satin"), + ] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":[name],"appearance":appearance})).unwrap(); + } + let group = + h.app.run("browser.group", json!({"folder":"bodies","name":"Spacer, fasteners","items":["Spacer","Bolt","Nut"]})).unwrap()["group"] + .as_u64() + .unwrap(); + h.app.tree.collapsed.insert(format!("c0/g{group}")); + for name in ["Hero", "Front", "Detail"] { + h.app.run("render.settings.set", json!({"name":name,"set":{"width":1920,"height":1080}})).unwrap(); + } + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_width = 266.0; + h.app.render_workspace.view.draft.width = 1920; + h.app.render_workspace.view.draft.height = 1080; + h.app.ui.dark = dark; + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Boss".into()}]})).unwrap(); + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + let mut images = Vec::new(); + for stage in ["look", "light"] { + h.app.run("view.render_stage", json!({"stage":stage})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.lights = Some(serde_json::from_value(json!([{"direction":[0,0,-1],"color":[1,1,1],"intensity":1},{"direction":[1,0,0],"color":[1,1,1],"intensity":1},{"direction":[0,1,0],"color":[1,1,1],"intensity":1}])).unwrap()); + for section in ["lights", "shots", "objects"] { + if (stage == "look" && section == "objects") || (stage == "light" && section == "lights") { + h.app.tree.collapsed.remove(&format!("render:tree:{section}")); + } else { + h.app.tree.collapsed.insert(format!("render:tree:{section}")); + } + } + if stage == "light" { + h.app + .run( + "view.render_select", + json!({"kind":"light","id":format!("{}:render.tree_directional:0",h.app.render_workspace.view.method.label())}), + ) + .unwrap(); + } + let mut image = None; + for frame in 0..12 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(bounds), + time: Some(ctx.cumulative_frame_nr() as f64 / 60.0), + focused: true, + ..Default::default() + }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 11 { + let card = crate::scenario::rect_of("browser:card").unwrap(); + assert!((card.width() - 266.0).abs() < 0.1); + let inspector = crate::scenario::rect_of("render:inspector").unwrap(); + let stage_panel = h.app.shell.workspace_panels["render:appearances"].0; + assert!((card.top() - inspector.top()).abs() < 0.1); + assert!((stage_panel.bottom() - inspector.bottom()).abs() < 0.1); + assert!((stage_panel.top() - card.bottom() - Tokens::get().space_8).abs() < 0.1); + assert!(card.height() <= 330.0, "Browser must stay within the fixed tree height: {card:?}"); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + assert!(header.contains_rect(crate::scenario::rect_of("render:tree:by-look").unwrap())); + assert!(crate::scenario::handle_at("render:browser-model").is_none()); + assert!(crate::scenario::handle_at("render:browser-library").is_none()); + for (name, row, _, _) in crate::browser::drawn_rows() { + assert!((row.height() - 28.0).abs() < 0.1, "{name}: {row:?}"); + } + if stage == "look" { + let row = crate::browser::drawn_rows().into_iter().find(|r| r.0 == "Boss").unwrap().1; + assert!((row.width() - (card.width() - 2.0)).abs() < 0.1); + assert!(crate::scenario::handle_at("eye:Boss").unwrap().x > row.right() - 24.0); + } + if std::env::var_os("SOLIDCRAFT_BROWSER_EVIDENCE").is_some() { + let full = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image = Some( + image::imageops::crop_imm(&full, card.left() as u32, card.top() as u32, card.width() as u32, card.height() as u32) + .to_image(), + ); + } + } + } + if let (Some(image), Ok(dir)) = (image, std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + std::fs::create_dir_all(&dir).unwrap(); + image.save(std::path::Path::new(&dir).join(format!("scene-{stage}-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + images.push(image); + } + } + if let (Some(look), Some(light), Ok(dir)) = (images.first(), images.get(1), std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + let mut pair = image::RgbaImage::new(look.width() + light.width(), look.height().max(light.height())); + image::imageops::overlay(&mut pair, look, 0, 0); + image::imageops::overlay(&mut pair, light, 266, 0); + pair.save(std::path::Path::new(&dir).join(format!("scene-stages-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + themes.push(images); + h.app.run("view.render_browser", json!({"search":true,"query":"Copper"})).unwrap(); + h.app.tree.collapsed.remove("render:tree:objects"); + h.frames(4); + let rows = crate::browser::drawn_rows(); + assert!(rows.iter().any(|r| r.0 == "Knob")); + assert!(!rows.iter().any(|r| r.0 == "Boss")); + h.app.run("view.render_browser", json!({"search":false})).unwrap(); + h.frames(3); + assert!(crate::browser::drawn_rows().iter().any(|r| r.0 == "Boss")); + for hidden in [true, false] { + h.step(&json!({"click":{"handle":"eye:Boss"}})).unwrap(); + assert_eq!(h.app.session.visibility.hidden_bodies.iter().any(|name| name == "Boss"), hidden); + } + } + if let (Some(light), Some(dark), Ok(dir)) = (themes.first(), themes.get(1), std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + for (index, stage) in ["look", "light"].iter().enumerate() { + let mut pair = image::RgbaImage::new(light[index].width() + dark[index].width(), light[index].height().max(dark[index].height())); + image::imageops::overlay(&mut pair, &light[index], 0, 0); + image::imageops::overlay(&mut pair, &dark[index], 266, 0); + pair.save(std::path::Path::new(&dir).join(format!("scene-{stage}-themes.png"))).unwrap(); + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn render_workspace_shots_modified_dot_update_and_revert_follow_only_camera() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Camera; + h.frames(3); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_none()); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + h.app.render_workspace.view.draft.width = 317; + h.frames(2); + assert!(!shots::camera_modified(&h.app, "Studio"), "output settings must not mark the camera"); + h.app.cam.yaw += 0.3; + h.frames(3); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_some()); + assert!(crate::scenario::handle_at("render:shots:update").is_some()); + h.step(&json!({"click":{"handle":"render:shots:update"}})).unwrap(); + h.frames(2); + let mut expected = saved.clone(); + expected.camera = h.app.cam; + assert_eq!(h.app.session.doc.render.setups["Studio"], expected, "Update must preserve saved output and lighting"); + assert_eq!(h.app.render_workspace.view.draft.width, 317, "Update must preserve the editor draft"); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_none()); + assert!(crate::scenario::handle_at("render:shots:update").is_none()); + h.app.cam.roll += 0.2; + h.frames(3); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:shots:revert"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.cam, expected.camera); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_workspace_shots_save_prompt_and_size_dropdown_use_existing_commands() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:shots:save"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + h.app.render_workspace.view.save_shot_name = Some("Hero".into()); + h.frames(3); + assert_eq!(crate::scenario::count_of("dialog:ok:enabled"), Some(1.0)); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(h.app.session.doc.render.setups.contains_key("Hero")); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc.render.setups["Hero"].camera, h.app.cam); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:shots:size"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:Full HD"}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1920, 1080)); + assert_eq!(h.app.session.doc, doc); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_workspace_shots_thumbnails_bound_invalidate_and_never_replace_results_or_history() { + use std::time::{Duration, Instant}; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + for index in 0..20 { + h.app.run("render.settings.set", json!({"name":format!("Shot {index:02}"),"set":{"camera":h.app.cam}})).unwrap(); + } + // A real completed frame stays available, including its exact PNG and retained texture. + let id = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(id); + cache_render_images(&mut h.app, &h.ctx); + h.app.render_workspace.view.job = None; + let png = h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + let retained = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let deadline = Instant::now() + Duration::from_secs(20); + while h.app.render_workspace.thumbnails.entries.len() < thumbnails::LIMIT { + assert!(Instant::now() < deadline, "thumbnail worker did not complete"); + thumbnails::refresh(&mut h.app, &h.ctx); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(h.app.render_workspace.thumbnails.entries.len(), 16); + assert!(h.app.render_workspace.thumbnails.entries.values().all(|texture| texture.as_ref().is_some_and(|texture| texture.size() == [104, 60]))); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), retained); + assert_eq!(h.app.render_workspace.view.completed, Some(id)); + assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), png); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(h.app.session.doc, doc); + assert_eq!(h.app.session.undo.len(), undo); + // Later shots must get previews on selection/scrolling rather than keeping the first 16 forever. + h.app.render_workspace.view.name = "Shot 19".into(); + h.app.render_workspace.thumbnails.show(vec!["Shot 18".into(), "Shot 19".into()], &h.ctx); + thumbnails::refresh(&mut h.app, &h.ctx); + while h.app.render_workspace.thumbnails.texture("Shot 19").is_none() || h.app.render_workspace.thumbnails.texture("Shot 18").is_none() { + assert!(Instant::now() < deadline, "visible thumbnail worker did not complete"); + thumbnails::refresh(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.thumbnails.entries.len() <= 16); + std::thread::sleep(Duration::from_millis(2)); + } + let old = h.app.render_workspace.thumbnails.entries.keys().cloned().collect::>(); + // Camera, scene revision and visibility invalidate stale previews. + let camera = Camera { yaw: 0.7, ..h.app.cam }; + h.app.run("render.settings.set", json!({"name":"Shot 00","set":{"camera":camera}})).unwrap(); + thumbnails::refresh(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.thumbnails.entries.keys().all(|key| !old.contains(key))); + h.app.session.visibility.hidden_bodies.push("Body1".into()); + thumbnails::refresh(&mut h.app, &h.ctx); + invalidate_scene(&mut h.app); + assert!(h.app.render_workspace.thumbnails.entries.is_empty()); + thumbnails::refresh(&mut h.app, &h.ctx); + reset_document(&mut h.app); + assert!(h.app.render_workspace.thumbnails.entries.is_empty()); +} + +#[test] +fn render_workspace_shots_running_ring_stays_with_the_submitted_shot() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.name = "A".into(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{}})).unwrap(); + h.app.start("render.start"); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("A")); + h.app.render_workspace.view.name = "B".into(); + h.frames(2); + assert!(crate::scenario::rect_of("dialog:list:shot:A:progress").is_some()); + assert!(crate::scenario::rect_of("dialog:list:shot:B:progress").is_none()); + h.app.start("render.cancel"); +} + +#[test] +fn render_workspace_shots_thumbnail_keys_include_name_scene_revision_and_complete_camera() { + let camera = Camera::default(); + let key = thumbnails::Key::new("Hero".into(), 1, 2, camera); + assert_eq!(key, thumbnails::Key::new("Hero".into(), 1, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Front".into(), 1, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Hero".into(), 2, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Hero".into(), 1, 3, camera)); + for changed in [ + Camera { yaw: camera.yaw + 0.1, ..camera }, + Camera { roll: camera.roll + 0.1, ..camera }, + Camera { fov: 0.7, ..camera }, + Camera { up: solidcraft_engine::render::UpAxis::Y, ..camera }, + ] { + assert_ne!(key, thumbnails::Key::new("Hero".into(), 1, 2, changed)); + } +} + +#[test] +fn render_workspace_shots_heading_matches_design_history_typography_and_strip_baseline() { + fn heading(h: &mut Harness, title: &str, strip: &str) -> (egui::FontId, Color32) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 1000.0))), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + let rect = crate::scenario::rect_of(strip).unwrap(); + let text = crate::test_support::text_shapes(&output).find(|text| text.galley.text() == title && rect.contains(text.pos)).unwrap(); + let format = &text.galley.job.sections.first().unwrap().format; + assert!((text.pos.y + text.galley.size().y / 2.0 - rect.center().y).abs() <= 1.0, "{title} centred on its strip"); + let appearance = (format.font_id.clone(), format.color); + output.textures_delta.clear(); + appearance + } + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.ui.layout = crate::shell::LayoutMode::Docked; + h.app.preferences.timeline_left = false; + h.app.ui.show_timeline = true; + h.frames(3); + let history = heading(&mut h, "History", "history:strip"); + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert_eq!(heading(&mut h, "Shots", "render:shots_strip"), history); +} + +#[test] +fn render_workspace_frame_save_shot_dispatches_without_a_ribbon_or_document_edits() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frames(3); + assert!(crate::scenario::handle_at("render:stage:save_shot").is_none()); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:stage:save_shot"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), undo); + h.app.render_workspace.view.save_shot_name = Some("Frame shot".into()); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Frame shot"].camera, h.app.cam); + h.app.render_workspace.view.save_shot_name = None; + assert!(h.app.run("render.settings.set", json!({})).is_err()); + assert!(!inspector::confirmation_open(&h.app)); + assert!(crate::workspace::destination(solidcraft_engine::find_command("view.shots_strip").unwrap()).is_none()); + assert!(crate::workspace::RIBBON_LABELS.iter().all(|(id, _)| *id != "view.shots_strip")); +} + +#[test] +fn render_workspace_shots_strip_geometry_and_theme_evidence() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.pending_fit = None; + for (name, yaw) in [("Hero", 0.5), ("Front", 0.0), ("Detail", 0.8)] { + h.app.run("render.settings.set", json!({"name":name,"set":{"camera":Camera {yaw,..h.app.cam}}})).unwrap(); + } + switch_shot(&mut h.app, "Hero".into()); + h.app.render_workspace.view.draft.width = 1920; + h.app.render_workspace.view.draft.height = 1080; + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":1920,"height":1080}})).unwrap(); + let id = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..10_000 { + host.pump(16_384).unwrap(); + if h.app.session.render_job_handle(id).unwrap().frame().unwrap().is_some() { + break; + } + } + assert!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().is_some()); + h.app.render_workspace.view.job = Some(id); + cache_render_images(&mut h.app, &h.ctx); + h.app.render_workspace.view.job = None; + h.app.ui.dark = dark; + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for frame in 0..12 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(bounds), time: Some(ctx.cumulative_frame_nr() as f64 / 60.0), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 11 { + let strip = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((strip.height() - 48.0).abs() < 1.0, "{strip:?}"); + let mut last = crate::scenario::rect_of("render:shots:heading").unwrap(); + for target in [ + "render:shots:save", + "render:shots:setup:Detail", + "render:shots:setup:Front", + "render:shots:setup:Hero", + "render:shots:status", + "render:shots:size", + "render:shots:render", + "render:shots:hide", + ] { + let rect = crate::scenario::rect_of(target).unwrap(); + assert!(strip.contains_rect(rect), "{target}: {rect:?} in {strip:?}"); + assert!(rect.left() >= last.right(), "{target} overlaps preceding control"); + last = rect; + } + if let Ok(dir) = std::env::var("SOLIDCRAFT_SHOTS_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let image = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image.save(std::path::Path::new(&dir).join(format!("shots-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn appearance_editor_hostile_optics_stay_finite_and_never_panic() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target = materials::read_targets(&mut h.app).unwrap().remove(0); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1e300] { + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + binding.glass.ior = value; + h.app.render_workspace.view.materials.bindings = vec![binding]; + assert!(materials::params(&h.app, &mut json!({})).is_err(), "hostile IOR {value}"); + } + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass.boundary = materials::Boundary::Box; + binding.glass.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + h.app.render_workspace.view.materials.bindings = vec![binding]; + assert!(materials::params(&h.app, &mut json!({})).is_ok(), "box boundaries are closed dielectrics too"); +} + +fn output_viewer_fixture() -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.frames(3); + h +} + +#[test] +fn output_viewer_size_chips_obey_limits_and_largest_upscales_at_the_current_aspect() { + let mut h = output_viewer_fixture(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for (key, expected) in [("720", (1280, 720)), ("1080", (1920, 1080))] { + h.step(&json!({"click":{"handle":format!("render:preset:{key}")}})).unwrap(); + let draft = &h.app.render_workspace.view.draft; + assert_eq!((draft.width, draft.height), expected); + } + let largest = inspector::largest_output(&h.app).unwrap(); + assert!(largest.0 > 1920); + assert_eq!(cpu::image_limits(&h.app).fit(largest.0, largest.1, None), Some(largest)); + assert!((largest.0 as f64 / largest.1 as f64 - 16.0 / 9.0).abs() < 0.002); + h.step(&json!({"click":{"handle":"render:size:largest"}})).unwrap(); + assert_eq!((u64::from(h.app.render_workspace.view.draft.width), u64::from(h.app.render_workspace.view.draft.height)), largest); + let before = h.app.render_workspace.view.draft.clone(); + assert!(h.app.run("render.output.size", json!({"width":4096,"height":4096})).is_err()); + assert_eq!(h.app.render_workspace.view.draft, before); + assert_eq!(h.app.session.doc.features, document.features); + assert_eq!(undo + 3, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_check_lists_preflight_results_without_starting_and_marks_edits_stale() { + let mut h = output_viewer_fixture(); + let host = h.app.session.render_job_host().unwrap().clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:stage:check"}})).unwrap(); + assert!(h.app.render_workspace.view.inspector.checked.is_none()); + h.step(&json!({"click":{"handle":"render:check"}})).unwrap(); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(undo, h.app.session.undo.len()); + for key in ["ready", "size", "transparency"] { + assert!(crate::scenario::rect_of(&format!("render:check:{key}")).is_some(), "{key}"); + } + h.app.run("render.output.size", json!({"width":32,"height":16})).unwrap(); + h.frames(2); + assert!(crate::scenario::rect_of("render:check:stale").is_some()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_copy_uses_retained_final_pixels_and_refuses_missing_or_oversized_images() { + let mut h = output_viewer_fixture(); + assert!(ribbon::perform_job(&mut h.app, "render.result.copy").is_err()); + assert!(h.app.render_workspace.clipboard_image.is_none()); + assert!(decode_render_image(&[], 4097, 1, RenderLimits::default(), 4096).unwrap_err().contains("resource profile")); + assert!(decode_render_image(&[], 4096, 4096, RenderLimits::default(), 4096).unwrap_err().contains("resource profile")); + let first = completed_preview(&mut h, [12, 34, 56]); + h.app.render_workspace.view.completed = Some(first); + // A new queued render must not become the source for Copy. + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + ribbon::perform_job(&mut h.app, "render.result.copy").unwrap(); + let image = h.app.render_workspace.clipboard_image.as_ref().unwrap(); + assert_eq!(image.size, [16, 16]); + assert_eq!(image.pixels[0], egui::Color32::from_rgb(12, 34, 56)); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frame(); + assert!(h.app.render_workspace.clipboard_image.is_none()); + assert!(h.output.commands.iter().any(|command| matches!(command, egui::OutputCommand::CopyImage(image) if image.size == [16,16]))); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(undo, h.app.session.undo.len()); +} + +#[test] +fn output_viewer_progress_keeps_stage_tools_and_cancel_cancels_without_closing_viewer() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.result = true; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:progress-pill").is_some()); + assert!(crate::scenario::rect_of("render:stage:size").is_some()); + assert!(crate::scenario::rect_of("render:hud").is_none()); + h.step(&json!({"click":{"handle":"render:progress-cancel"}})).unwrap(); + h.app.session.render_job_host().unwrap().pump(1024).unwrap(); + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "cancelled"); + assert!(h.app.render_workspace.view.result); + h.frames(3); + assert!(crate::scenario::rect_of("render:progress-pill").is_none()); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + assert!(crate::scenario::handle_at("render:pick").is_some()); +} + +#[test] +fn output_viewer_r_starts_active_setup_and_escape_returns_to_model_without_cancelling() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.name = "Active shot".into(); + h.app.render_workspace.view.draft.width = 32; + h.app.render_workspace.view.draft.height = 24; + assert_eq!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); + h.step(&json!({"key":"R"})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("Active shot")); + let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(status["request"]["width"], 32); + assert_eq!(status["request"]["height"], 24); + // A repeated R while busy cannot fall through to Rectangle/Create Sketch. + h.step(&json!({"key":"R"})).unwrap(); + assert_eq!(h.app.render_workspace.view.job, Some(job)); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.frames(2); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.result); + assert!(ribbon::busy(&h.app), "closing the image never cancels the job"); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.app.viewport.nav = Some(crate::viewport::NavMode::Pan); + crate::keymap::press(&mut h.app, "Escape", false); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.viewport.nav.is_none(), "closing the image releases its navigation capture"); + enter(&mut h.app, false).unwrap(); + assert_ne!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); +} + +/// Actual app controls and retained pixels, rasterized from egui without a window. +#[test] +fn output_viewer_evidence() { + let Some(dir) = std::env::var_os("SOLIDCRAFT_OUTPUT_EVIDENCE") else { return }; + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = output_viewer_fixture(); + h.app.run("solid.box", json!({"length":24,"width":18,"height":12})).unwrap(); + inspector::fit_subject(&mut h.app).unwrap(); + h.app.pending_fit = None; + h.app.cancel_view_animation(); + h.app.preferences.render_inspector_width = 305.0; + h.app.run("render.output.size", json!({"width":1280,"height":720})).unwrap(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + h.ctx = crate::fonts::test_context(); + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.dark = dark; + crate::theme::set_dark(dark); + crate::theme::apply(&h.ctx); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for (index, state) in ["settings", "check", "effects", "running", "completed"].into_iter().enumerate() { + if state == "check" { + h.app.run("view.render_select", json!({"kind":"check"})).unwrap(); + h.app.cancel_view_animation(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + } + if state == "effects" { + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.start("render.effects.describe"); + } + if state == "running" { + select_image_method(&mut h.app, ImageMethod::Raster); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + // Retain a real first image while the next job makes bounded progress. + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..1000 { + if !host.pump(65536).unwrap() { + break; + } + } + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.completed.is_some()); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + host.pump(327680).unwrap(); + assert!(ribbon::busy(&h.app)); + } + if state == "completed" { + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..1000 { + if !host.pump(65536).unwrap() { + break; + } + } + } + for frame in 0..10 { + let mut events = Vec::new(); + if frame == 0 { + events.push(egui::Event::PointerMoved(egui::pos2(700.0, 500.0))); + } + let mut input = egui::RawInput { + screen_rect: Some(bounds), + focused: true, + time: Some((index * 10 + frame) as f64 / 60.0), + events, + ..Default::default() + }; + h.app.raw_input_hook(&mut input); + let mut output = h.ctx.run_ui(input, |ui| { + h.app.logic(ui.ctx()); + if state == "check" && frame == 9 { + // Check the settled, scrolled view immediately before capturing it. + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + } + h.app.ui(ui); + }); + crate::ui_kit::update_test_textures(&mut textures, &output.textures_delta); + if frame == 9 { + if state == "check" { + for key in ["ready", "size", "transparency"] { + assert!(crate::scenario::rect_of(&format!("render:check:{key}")).is_some(), "{key}"); + } + assert!(h.app.render_workspace.view.job.is_none()); + } + crate::ui_kit::raster_ui(&h.ctx, output.shapes.clone(), output.pixels_per_point, bounds, &textures) + .save(dir.join(format!("output-{state}-{}.png", if dark { "dark" } else { "light" }))) + .unwrap(); + } + output.textures_delta.clear(); + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn output_viewer_radial_defaults_enable_lights_and_keep_planned_compare_disabled() { + let h = output_viewer_fixture(); + let expected = [ + "render.start", + "appearance.assign", + "render.lights.add", + "render.settings.set", + "render.camera.fit", + "render.compare", + "ui.workspace.design", + "undo", + ]; + assert_eq!(crate::mouse_gesture::Studio::Render.defaults(), expected); + assert!(crate::mouse_gesture::item(&h.app, "render.lights.add").unwrap().enabled); + assert!(!crate::mouse_gesture::item(&h.app, "render.compare").unwrap().enabled); +} + +#[test] +fn output_viewer_presets_are_commands_with_limits_and_custom_keeps_the_size() { + let mut h = output_viewer_fixture(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frames(6); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "opening Size presets does not apply anything"); + for (index, (key, expected)) in [("720", (1280, 720)), ("1080", (1920, 1080)), ("square", (2048, 2048))].into_iter().enumerate() { + h.step(&json!({"click":{"handle":format!("render:preset:{key}")}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), expected); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + let saved = &h.app.session.doc.render.setups[&h.app.render_workspace.view.name]; + assert_eq!((saved.width, saved.height), expected); + } + h.step(&json!({"click":{"handle":"render:preset:4k"}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + h.step(&json!({"click":{"handle":"render:preset:custom"}})).unwrap(); + assert!(h.app.render_workspace.view.inspector.resolution.custom); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + assert_eq!(document.features, h.app.session.doc.features); + assert_eq!(undo + 3, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_has_sections_without_pages_or_footer_and_selected_row_routes_to_output() { + for dark in [false, true] { + let mut h = output_viewer_fixture(); + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.dark = dark; + h.call("ui.resize", json!({"width":1440,"height":900})); + h.frames(3); + for key in ["render.children.renderer", "render.output_image", "render.output_destination", "render.children.render"] { + assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).is_some(), "{key}"); + } + assert!(crate::scenario::rect_of("render:job-footer").is_none()); + for page in ["output", "effects", "all"] { + assert!(crate::scenario::rect_of(&format!("render:page:{page}")).is_none()); + } + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for target in ["render:stage:size", "render:stage:check"] { + assert!(tools.contains_rect(crate::scenario::rect_of(target).unwrap())); + } + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:output-width").is_some(), "selected Output keeps its editor when the stage changes"); + } +} + +#[test] +fn render_assign_gestures_selection_sizes_are_atomic_and_undoable() { + use solidcraft_engine::Sel; + let (mut h, occurrence) = render_pick_sample(); + for mode in ["body", "face", "component"] { + h.app.run("select.filter", json!({"mode":mode})).unwrap(); + let at = product_pick_point(&h); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), false).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + match mode { + "body" => assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Blue"), + "face" => assert!(h.app.session.doc.appearances.faces.iter().any(|f| f.look.name == "ABS - Blue")), + _ => { + let id = h.app.session.doc.path_placement(&[occurrence]).unwrap().0; + assert_eq!(h.app.session.doc.appearances.components[&id].name, "ABS - Blue"); + } + } + assert!(h.app.status_undo); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + } + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Plate".into() }, Sel::Body { name: "missing".into() }]; + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + assert!(assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), false).is_err()); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_assign_gestures_paint_sample_copy_paste_escape_and_failed_pick() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + let before = h.app.session.doc.clone(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), false).unwrap(); + assert!(h.app.render_workspace.view.assign.painting); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + h.frames(3); + let at = product_pick_point(&h); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 2); + h.step(&json!({"widget":"Undo"})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1, "toast Undo must not paint through to the canvas"); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting); + h.app.run("appearance.assign", json!({"body":"Plate","faces":[[20,20,8]],"appearance":"ABS - Blue"})).ok(); + h.app.start("appearance.pick_up"); + let candidate = crate::viewport::pick(&h.app, &crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()), at) + .into_iter() + .find(|hit| matches!(hit, crate::viewport::Hit::Face { .. })) + .unwrap(); + let source = match candidate { + crate::viewport::Hit::Face { body, index, .. } => Some((body, index)), + _ => None, + }; + let (body, index) = source.unwrap(); + let expected = h.app.run("appearance.pick_up", json!({"target":{"body":body,"face":index}})).unwrap()["look"].clone(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert!(h.app.render_workspace.view.assign.painting); + assert_eq!(h.app.render_workspace.view.assign.look, Some(expected.clone())); + h.step(&json!({"widget":"Done"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting); + h.app.start("appearance.paint"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Plate".into() }]; + h.app.start("appearance.copy"); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Yellow"})).unwrap(); + let undo = h.app.session.undo.len(); + h.app.start("appearance.paste"); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Red"); + h.app.start("appearance.pick_up"); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + // Empty view: a failed pick neither paints nor exits sampling. + let free = crate::render_ui::canvas(&h.app, h.app.viewport.rect.unwrap()); + let empty = egui::pos2(free.right() - 20.0, free.bottom() - 50.0); + h.step(&json!({"click":[empty.x,empty.y]})).unwrap(); + assert!(h.app.render_workspace.view.assign.sampling); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.sampling); +} + +#[test] +fn render_assign_gestures_drag_preview_and_release_use_no_document_draft() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + let at = product_pick_point(&h); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + ]); + h.frames(2); + assert!(assign::preview(&h.app).is_some()); + let mut scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let before = scene.meshes.iter().map(|m| m.color).collect::>(); + assign::preview_scene(&mut scene, assign::preview(&h.app).as_ref()).unwrap(); + assert_ne!(scene.meshes.iter().map(|m| m.color).collect::>(), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.frame_with(vec![egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }]); + h.frames(2); + assert!(assign::preview(&h.app).is_none()); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Blue"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), document.to_json()); +} + +#[test] +fn render_assign_gestures_shortcuts_are_scoped_and_commands_are_not_stubs() { + let mut h = Harness::new(); + assert_eq!(crate::keymap::command_for(&h.app, "I"), Some("inspect.measure")); + enter(&mut h.app, true).unwrap(); + assert_eq!(crate::keymap::command_for(&h.app, "I"), Some("appearance.pick_up")); + assert_eq!(crate::keymap::command_for(&h.app, "B"), Some("appearance.paint")); + for (id, key) in [("appearance.copy", "Ctrl+Alt+C"), ("appearance.paste", "Ctrl+Alt+V")] { + assert_eq!(crate::keymap::command_for(&h.app, key), Some(id)); + } + for id in ["appearance.paint", "appearance.pick_up", "appearance.copy", "appearance.paste"] { + assert!(solidcraft_engine::find_command(id).unwrap().planned.is_none()); + } + let before = h.app.session.doc.clone(); + h.app.run("appearance.paint", json!({"appearance":"ABS - Red"})).unwrap(); + h.app.run("appearance.pick_up", json!({})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(h.app.dialog.is_none()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); +} + +#[test] +fn render_assign_gestures_grid_drag_modifiers_cancel_and_context_menu() { + let (mut h, occurrence) = render_pick_sample(); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"name":"Gesture blue","color":"#1234dd"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + h.step(&json!({"click":{"handle":"render:library-scope:in-design"}})).unwrap(); + h.frames(3); + let id = json!(["Gesture blue", "#1234dd", 1.0, null]).to_string(); + let source = crate::scenario::rect_of(&format!("render:library:{id}")).unwrap().center(); + let at = product_pick_point(&h); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frame_with(vec![egui::Event::PointerMoved(source)]); + h.frame_with(vec![egui::Event::PointerButton { + pos: source, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }]); + h.frame_with(vec![egui::Event::PointerMoved(source + egui::vec2(20.0, 0.0))]); + h.frame_with(vec![egui::Event::PointerMoved(at)]); + h.frames(2); + assert!(assign::preview(&h.app).is_some(), "grid drag must arm a live preview over geometry"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + for mods in [egui::Modifiers::SHIFT, egui::Modifiers::CTRL, egui::Modifiers::COMMAND] { + h.frame_with(vec![egui::Event::ModifiersChanged(mods)]); + h.frames(2); + let hover = assign::hover(&h.app).unwrap(); + if mods.shift { + assert!(matches!(hover, solidcraft_engine::Sel::Face { .. })); + } else { + assert_eq!(hover, &solidcraft_engine::Sel::Occurrence { path: vec![occurrence] }); + } + assert!(assign::preview(&h.app).is_some()); + } + h.frame_with(vec![ + egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::SHIFT }, + ]); + h.frames(2); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.faces.last().unwrap().look.name, "Gesture blue"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), doc.to_json()); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), true).unwrap(); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(assign::preview(&h.app).is_none()); + assert_eq!(h.app.session.doc.to_json(), doc.to_json()); + let menu = assign::menu(&h.app, "Plate"); + for id in ["appearance.library", "appearance.pick_up", "appearance.copy", "appearance.paste", "appearance.assign"] { + assert!(menu.children.iter().any(|item| item.id == id), "missing menu action {id}"); + } + let browse = menu.children.iter().find(|item| item.id == "appearance.library").unwrap(); + crate::context_menu::run_item(&mut h.app, browse, at); + assert!(h.app.dialog.is_none()); + assert!(!h.app.render_workspace.view.assign.painting); +} + +#[test] +fn render_assign_gestures_labels_translate_in_all_five_catalogs() { + for language in ["en", "ja", "zh", "de", "ko"] { + let locale = crate::i18n::Locale::for_language(language); + for id in [ + "cmd.appearance_copy", + "cmd.appearance_paste", + "render.assign_help", + "render.browse_looks", + "render.choose_look", + "render.look_applied", + "render.painting_with", + "render.pick_up_prompt", + "render.recent_looks", + "render.remove_override", + "cmd.appearance_favorite", + "render.replace_all", + "render.replace_with", + "render.look_material", + "render.hover_look", + ] { + assert_ne!(locale.text(id), id, "{language}: {id}"); + } + assert!(locale.format("render.painting_with", &[("name", "Sample")]).contains("Sample")); + } +} + +#[test] +fn render_lighting_group_selection_opens_ordered_editor_and_plus_still_adds() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + let before = h.app.session.doc.clone(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:lights"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); + assert!(crate::scenario::rect_of("render:lighting:editor").is_some()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + let sections: Vec<_> = ["render.lighting_source_section", "render.lighting_shadows_section", "render.lighting_budget"] + .iter() + .map(|key| crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap()) + .collect(); + assert!(sections.windows(2).all(|pair| pair[0].bottom() <= pair[1].top())); + h.step(&json!({"click":{"handle":"render:tree:lights:add"}})).unwrap(); + assert!(light::rows(&h.app).unwrap().iter().any(|l| l.geometry.kind() == "area")); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("area:0".into())); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); +} + +#[test] +fn render_lighting_methods_show_reasons_and_budgets_without_changing_method_or_design() { + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + if method == ImageMethod::GpuRaytrace { + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{}}}}})).unwrap(); + setups::load(&mut h.app); + } else { + h.app.render_workspace.view.method = method; + } + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + let before = h.app.session.doc.clone(); + let revision = h.app.session.revision; + h.frames(3); + for section in ["render.lighting_source_section", "render.lighting_shadows_section", "render.lighting_budget"] { + assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(section))).is_some()); + } + let reason = match method { + ImageMethod::Raster => "render.method_limit_raster", + ImageMethod::CpuRaytrace => "render.lighting_samples_need_area", + ImageMethod::GpuRaytrace => "render.light_gpu_punctual", + }; + assert!(crate::scenario::rect_of(&format!("dialog:note:{reason}")).is_some()); + if method == ImageMethod::GpuRaytrace { + assert!(crate::scenario::rect_of("dialog:note:render.lighting_shadow_cpu").is_some()); + assert!(crate::scenario::rect_of("dialog:note:render.lighting_samples_cpu").is_some()); + } + assert!(h.widget(h.app.tr("render.lighting_budget_help")).is_some()); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.session.revision, revision); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(h.app.dialog.is_none() && h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn render_assign_gestures_stage_tools_and_selection_actions_use_commands() { + let (mut h, _) = render_pick_sample(); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Blue"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for id in ["appearance.paint", "appearance.pick_up"] { + assert!(tools.contains_rect(crate::scenario::rect_of(&format!("render:stage:{id}")).unwrap())); + assert!(crate::workspace::destination(solidcraft_engine::find_command(id).unwrap()).is_none()); + } + let pill = crate::scenario::rect_of("render:selection").unwrap(); + assert!((pill.height() - 34.0).abs() < 1.0, "{pill:?}"); + assert!(pill.width() < 200.0, "{pill:?}"); + for index in 0..4 { + assert!(pill.contains_rect(crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap())); + } + h.step(&json!({"click":{"handle":"render:stage:appearance.pick_up"}})).unwrap(); + assert!(h.app.render_workspace.view.assign.sampling); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"click":{"handle":"selection:action:0"}})).unwrap(); + assert!(crate::scenario::rect_of("render:look_chain").is_some()); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert_eq!(h.app.preferences.render_library_favorites.len(), 1); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert!(h.app.preferences.render_library_favorites.is_empty()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"selection:action:1"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + h.step(&json!({"click":{"handle":"dialog:Replace with"}})).unwrap(); + h.step(&json!({"widget":"Copper"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "Copper"); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"selection:action:3"}})).unwrap(); + assert!(!h.app.session.body_visible("Plate")); + h.app.run("edit.undo", json!({})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:selection").is_none()); + assert!(crate::scenario::rect_of("render:stage:appearance.paint").is_none()); +} + +#[test] +fn render_assign_gestures_replacement_draft_cannot_cross_a_document_edit() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.app.start("appearance.replace"); + assert!(assign::replacement_open(&h.app)); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Red"})).unwrap(); + h.frames(3); + assert!(!assign::replacement_open(&h.app)); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Red"); +} + +#[test] +fn render_assign_gestures_geometry_and_theme_evidence() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.cylinder", json!({"body_name":"Boss","radius":10,"height":20})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Boss"],"appearance":"Aluminum - Anodized Blue"})).unwrap(); + h.app.run("solid.sphere", json!({"body_name":"Knob","center":[0,0,28],"radius":8})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Knob"],"appearance":"Copper"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Boss".into()}]})).unwrap(); + h.app.pending_fit = None; + h.app.ui.dark = dark; + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for frame in 0..48 { + crate::scenario::clear_handles(); + let events = h + .app + .viewport + .rect + .and_then(|rect| crate::viewport::projection(&h.app, rect).to_screen(solidcraft_engine::geom::Vec3::new(0.0, 0.0, 28.0))) + .filter(|_| frame == 1) + .map(|at| vec![egui::Event::PointerMoved(at)]) + .unwrap_or_default(); + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), time: Some(frame as f64 / 60.0), events, ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 47 { + assert!( + crate::scenario::rect_of("kit:tooltip").is_some(), + "the model hover uses the standard kit tooltip; hover: {:?}, pointer: {:?}", + h.app.viewport.hover, + ctx.pointer_hover_pos() + ); + let tooltip = crate::scenario::rect_of("kit:tooltip").unwrap(); + assert!(tooltip.distance_to_pos(ctx.pointer_hover_pos().unwrap()) < Tokens::get().control_height, "{tooltip:?}"); + let pill = crate::scenario::rect_of("render:selection").unwrap(); + assert!((pill.height() - 34.0).abs() < 1.0, "{pill:?}"); + assert!((150.0..170.0).contains(&pill.width()), "{pill:?}"); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for id in ["appearance.paint", "appearance.pick_up"] { + assert!(tools.contains_rect(crate::scenario::rect_of(&format!("render:stage:{id}")).unwrap())); + } + if let Ok(dir) = std::env::var("SOLIDCRAFT_GESTURES_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let image = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image.save(std::path::Path::new(&dir).join(format!("look-controls-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn render_lights_each_kind_contains_design_sections_and_real_parameter_fields_in_order() { + for (method, kind) in + [("cpu_raytrace", "area"), ("cpu_raytrace", "point"), ("cpu_raytrace", "directional"), ("gpu_path", "area"), ("gpu_path", "directional")] + { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + let options = if method == "gpu_path" { json!({"lighting":{}}) } else { json!({"lights":[],"punctual_lights":[],"area_lights":[]}) }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":method,"options":options}}})).unwrap(); + setups::load(&mut h.app); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":kind}))).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + let before = h.app.session.doc.clone(); + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + let mut sections = vec!["render.light_position"]; + if kind == "area" { + sections.push("render.lighting_shape"); + } + if kind == "point" { + sections.push("render.lighting_falloff"); + } + sections.push("render.light_behaviour"); + let rects: Vec<_> = sections.iter().map(|key| crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap()).collect(); + assert!(rects.windows(2).all(|pair| pair[0].bottom() <= pair[1].top()), "{method}/{kind}"); + let fields: &[&str] = match kind { + "area" => &["width_mm", "height_mm", "radiance:0", "edge_u_mm:0", "edge_v_mm:0", "position_mm:0"], + "point" => &["reference_distance_mm", "minimum_distance_mm", "position_mm:0"], + _ => &["direction:0", "direction:1", "direction:2"], + }; + for field in fields { + assert!(crate::scenario::rect_of(&format!("render:light:{field}")).is_some(), "{method}/{kind}: {field}"); + } + for key in ["render.lighting_solo", "render.lighting_mute", "render.light_duplicate", "render.light_delete"] { + assert!(h.widget(h.app.tr(key)).is_some(), "{method}/{kind}: {key}"); + } + assert!(crate::scenario::rect_of("dialog:note:render.light_place_pending").is_some()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + } +} + +#[test] +fn render_lighting_preset_materialises_values_and_replacement_requires_review_consent() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + let before = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:lighting:preset"}})).unwrap(); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + // Confirm's primary action is disabled until its explicit acknowledgement. + h.step(&json!({"widget":h.app.tr("render.lighting_consent")})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.lighting_apply")})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.preset.is_some()); + assert!(h.app.render_workspace.view.raytrace.lights.is_none()); + let lights = light::rows(&h.app).unwrap(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:lighting:custom"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.preset.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.lights.as_ref().unwrap().len(), lights.len()); + let materialised = light::rows(&h.app).unwrap(); + for (before, after) in lights.iter().zip(materialised) { + assert_eq!(before.colour, after.colour); + assert_eq!(before.intensity, after.intensity); + } + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); +} + +#[test] +fn render_lighting_hostile_numeric_edits_refuse_without_panics_or_partial_state() { + let mut h = render_lights_fixture(); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":"point"}))).unwrap(); + let before = h.app.session.doc.clone(); + let history = h.app.session.undo.len(); + for set in + [json!({"reference_distance_mm":1e300}), json!({"minimum_distance_mm":-1}), json!({"position_mm":[1e300,0,0]}), json!({"direction":[0,0,0]})] + { + assert!(light::edit(&mut h.app, "render.lights.set", Some("point:0"), Some(set)).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), history); + } + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); +} + +#[test] +fn render_lighting_shadow_edits_are_undoable_and_preset_reviews_reject_changed_drafts() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":h.app.tr("render.lighting_shadows")})).unwrap(); + assert!(!h.app.render_workspace.view.raytrace.shadows); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(matches!(&h.app.session.doc.render.setups["Studio"].job, + Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options }) if !options.shadows)); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.session.doc, before); + h.frames(3); + h.step(&json!({"click":{"handle":"render:lighting:preset"}})).unwrap(); + assert!(h.widget(h.app.tr("render.lighting_consent")).is_some()); + h.app.render_workspace.view.draft.width = 1200; + h.frames(3); + assert!(h.widget(h.app.tr("render.lighting_consent")).is_none()); + assert_eq!(h.app.session.doc, before); + assert_eq!(h.app.render_workspace.view.draft.width, 1200); +} + +#[test] +fn geometry_budget_follows_the_device_buffer_limit_and_keeps_the_web_cap() { + // The standard 256 MiB device buffers: 2 GiB, far past the old fixed 128 MiB. + assert_eq!(geometry_budget(256 << 20, false), 2 << 30); + assert!(admit_geometry(129 << 20, geometry_budget(256 << 20, false)).is_ok()); + // A smaller device gets less, a larger one no more than the ceiling. + assert_eq!(geometry_budget(64 << 20, false), 512 << 20); + assert_eq!(geometry_budget(u64::MAX, false), DESKTOP_GEOMETRY_CEILING); + for device in [0, 256 << 20, u64::MAX] { + let budget = geometry_budget(device, true); + assert_eq!(budget, 128 << 20); + assert!(admit_geometry(budget, budget).is_ok()); + assert!(admit_geometry(budget + 1, budget).is_err()); + } +} + +#[test] +fn geometry_refusal_reports_scene_size_limit_and_recovery() { + use solidcraft_engine::{ + geom::{Aabb3, Mesh}, + render::ProductMesh, + }; + let scene = ProductScene { + meshes: vec![ProductMesh { + name: "Synthetic assembly".into(), + mesh: Arc::new(Mesh { triangles: vec![[0; 3]; 1 << 20], ..Default::default() }), + color: [128; 3], + opacity: 1.0, + surface: Some( + solidcraft_engine::render::surface::OpaqueSurface::new(solidcraft_engine::geom::Vec3::new(0.5, 0.5, 0.5), 0.0, 0.5, 1.5).unwrap(), + ), + transmission: None, + faces: Vec::new(), + }], + bounds: Aabb3::EMPTY, + }; + let error = gpu_scene_with_budget(&scene, WEB_GEOMETRY_BYTES).err().unwrap(); + assert!(error.contains("144.0 MiB"), "{error}"); + assert!(error.contains("128.0 MiB"), "{error}"); + assert!(error.contains("Hide bodies in Design"), "{error}"); + let refused = upload_refusal(144 << 20, "Out of Memory"); + assert!(refused.contains("144.0 MiB") && refused.contains("Out of Memory") && refused.contains("Hide bodies in Design"), "{refused}"); +} + +#[test] +fn previous_geometry_budget_restores_the_fixed_limit() { + for web in [false, true] { + for device in [64 << 20, 256 << 20, u64::MAX] { + let device_budget = geometry_budget(device, web); + assert_eq!(preferred_geometry_budget(device_budget, false), device_budget); + let previous = preferred_geometry_budget(device_budget, true); + assert_eq!(previous, MAX_GEOMETRY_BYTES as u64); + assert!(admit_geometry(previous, previous).is_ok()); + assert!(admit_geometry(previous + 1, previous).is_err()); + } + } +} + +#[test] +fn geometry_budget_change_retries_cached_admission_without_document_changes() { + let mut session = Session::default(); + session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&session).unwrap(); + let bytes = preview_upload_plan(&scene, usize::MAX).unwrap().bytes().unwrap() as u64; + let mut state = State::default(); + assert!(state.prepare_preview((7, 123, 99, bytes - 1), || Ok(scene.clone())).is_err()); + state.prepare_preview((7, 123, 99, bytes), || Ok(scene)).unwrap(); + assert_eq!(state.preview_upload_bytes, Some(bytes as usize)); + assert!(state.scene_error.is_none()); +} + +#[test] +fn cpu_interactive_cold_assembly_binding_refuses_without_preparing_world() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + let component = h.app.session.execute("component.create", &json!({"name":"Part","grounded":false})).unwrap(); + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let initial = h.app.session.world_state(); + let name = initial.bodies[0].name.clone(); + cpu::set_reflection(&mut h.app, &name, Some(ReflectionMode::Mirror)).unwrap(); + // Exact placement metadata changes without running a UI paint or world query. + let occurrence: u64 = serde_json::from_value(component["occurrence"].clone()).unwrap(); + h.app.session.pending_moves.insert(occurrence, solidcraft_engine::doc::IDENTITY); + assert!(h.app.session.interactive_cached_world_state().is_none()); + let model = h.app.session.model.state(); + assert!(model.bodies.iter().all(|body| body.cached_mesh().is_none())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!(h.app.session.interactive_cached_world_state().is_none(), "binding proof must not prepare cold placements"); + assert!(model.bodies.iter().all(|body| body.cached_mesh().is_none())); + cpu::set_reflection(&mut h.app, &name, None).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(h.app.session.interactive_cached_world_state().is_none(), "empty reflections need no prepared world"); +} + +#[test] +fn interactive_egui_clock_is_finite_monotonic_and_requires_no_platform_instant() { + use std::time::Duration; + let mark = Duration::from_secs(2); + for time in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1.0, f64::MAX] { + assert_eq!(interactive::monotonic(mark, time), mark); + } + assert_eq!(interactive::monotonic(mark, 3.5), Duration::from_millis(3500)); +} + +fn interactive_control_frame(h: &mut Harness, time: f64, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(time), + events, + ..Default::default() + }, + |ui| { + ui.set_width(300.0); + interactive::before_paint(&mut h.app, ui.ctx()); + interactive::controls(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} + +#[test] +fn interactive_is_opt_in_and_refuses_raster_or_cooperative_hosts_without_fallback() { + let mut h = Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + let document = h.app.session.doc.clone(); + let path = matches!(h.app.render_workspace.path_host, PathHost::NotStarted); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + interactive_control_frame(&mut h, 1.0, vec![]); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted), path); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_ui_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":8,"height":4,"body_name":"Subject"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host)).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + // Do not enter through a deferred GPU factory in CPU-only adapter tests. + h.app.ui.tab = "RENDER".into(); + h +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_test_cpu_branch(h: &mut Harness, case: &str) -> bool { + let host = h.app.session.render_job_host().unwrap(); + let supported = host.kind() == solidcraft_engine::render::job::HostKind::NativeWorker + && host.is_available() + && host.validate_integrator(Integrator::Raytrace).is_ok(); + if supported { + eprintln!("INTERACTIVE_BRANCH case={case} cpu_supported=true"); + return true; + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + eprintln!("INTERACTIVE_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + false +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_runtime_builder_preserves_hdr_ev_and_muted_lights_without_final_dimension_admission() { + let mut h = interactive_ui_fixture(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.settings.set", json!({"name":name,"set":{"job":{"method":"cpu_raytrace"}}})).unwrap(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.cpu.hdr.embedded()); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.raytrace.shadows = false; + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + let before = h.app.session.doc.clone(); + let wire = interactive_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["width"], 3840, "engine must fit before admission"); + assert!(wire["settings"]["job"].is_null()); + assert_eq!(wire["settings"]["exposure_ev"], 0.0); + assert_eq!(wire["raytrace"]["exposure_ev"], 1.5); + assert_eq!(wire["raytrace"]["shadows"], false); + assert_eq!(wire["raytrace"]["lights"][0]["intensity"], 0.0); + assert_eq!(wire["environment"]["resource"], json!(h.app.render_workspace.view.cpu.hdr.resource().unwrap())); + assert!(wire["environment"].get("path").is_none()); + assert!(raw_image_request(&h.app).is_err(), "final admission must remain unchanged"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_identity_tracks_camera_transport_and_visibility_before_paint_without_dispatching() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_identity_tracks_camera_transport_and_visibility_before_paint_without_dispatching") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_control_frame(&mut h, 0.0, vec![]); + let first = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let revision = h.app.session.revision; + h.app.cam.yaw += 0.2; + interactive_control_frame(&mut h, 0.5, vec![]); + let camera = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(camera > first); + h.app.render_workspace.view.raytrace.shadows = false; + interactive_control_frame(&mut h, 1.0, vec![]); + let transport = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(transport > camera); + h.app.session.visibility.hidden_bodies.push("Subject".into()); + interactive_control_frame(&mut h, 1.5, vec![]); + let visibility = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(visibility > transport); + assert_eq!(h.app.session.revision, revision, "all three edits deliberately bypass CAD revision"); + assert_eq!(interactive::inspect(&h.app)["pending_capture"], false, "before_paint never dispatches a worker"); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_command_controls_pause_resume_and_leave_without_changing_final_slots() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_command_controls_pause_resume_and_leave_without_changing_final_slots") { + return; + } + interactive_control_frame(&mut h, 0.0, vec![]); + let mut time = 0.01; + for action in ["on", "pause", "resume", "off"] { + let rect = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap(); + let at = rect.center(); + interactive_control_frame( + &mut h, + time, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }, + ], + ); + time += 0.01; + interactive_control_frame(&mut h, time, vec![]); + time += 0.01; + assert_eq!(interactive::inspect(&h.app)["enabled"], action != "off"); + assert_eq!(interactive::inspect(&h.app)["paused"], action == "pause"); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.view.result); + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + enter(&mut h.app, false).unwrap(); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); +} + +#[test] +fn interactive_reset_retains_one_real_receiver_and_discards_its_late_foreign_error() { + use solidcraft_engine::render::job::interactive::{Interactive, VisualRevision}; + use std::{sync::mpsc, time::Duration}; + let mut h = Harness::new(); + let mut controller = Interactive::new(7001); + controller.enable(VisualRevision { scene_generation: 0, visual_revision: 1 }, Duration::ZERO).unwrap(); + let ticket = controller.capture(Duration::from_millis(200)).unwrap().unwrap(); + let (sender, receiver) = mpsc::channel(); + h.app.render_workspace.interactive.pending = Some(interactive::Pending { uid: h.app.session.uid, ticket, receiver }); + reset_document(&mut h.app); + assert!(h.app.render_workspace.interactive.pending()); + reset_document(&mut h.app); + assert!(h.app.render_workspace.interactive.pending(), "a second document reset cannot orphan the pending worker"); + sender.send(Err("late old capture".into())).unwrap(); + interactive_control_frame(&mut h, 1.0, vec![]); + assert!(!h.app.render_workspace.interactive.pending()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert!(interactive::inspect(&h.app)["error"].is_null()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_background_final_metadata_suspends_without_cancelling_queued_final() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_background_final_metadata_suspends_without_cancelling_queued_final") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + let job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(host.clone())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + serde_json::from_value::(reply["job"].clone()).unwrap() + }; + let retained = host.admitted_bytes(); + interactive_control_frame(&mut h, 1.0, vec![]); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + let background = h.app.docs.background().next().unwrap(); + assert_eq!(background.render_job_handle(job).unwrap().status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + assert_eq!(host.admitted_bytes(), retained); + assert!(!h.app.render_workspace.interactive.pending()); +} + +// Native CPU acceptance of the real M3 dispatcher; no native window or GPU. +#[cfg(not(target_arch = "wasm32"))] +struct InteractiveHeldCallback { + job: solidcraft_engine::render::job::JobHandle, + sender: std::sync::mpsc::Sender>, + reply: Result, +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_acceptance_frame(h: &mut Harness, time: f64, dispatch: bool, paint: bool) -> (egui::FullOutput, bool) { + let mut painted = false; + let output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(time), + ..Default::default() + }, + |ui| { + // tick dispatches through the actual production spawn(Snapshot) path. + // Do not run a second refresh here: the callback must be held before UI delivery. + if dispatch { + interactive::tick(&mut h.app, ui.ctx()); + } else { + interactive::before_paint(&mut h.app, ui.ctx()); + } + if paint { + painted = interactive::paint(&h.app, ui, ui.max_rect()); + } + }, + ); + (output, painted) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_clear_acceptance_frame(h: &mut Harness, time: f64, dispatch: bool) { + let (mut output, painted) = interactive_acceptance_frame(h, time, dispatch, false); + assert!(!painted); + output.textures_delta.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_hold_real_completed_callback(h: &mut Harness) -> InteractiveHeldCallback { + use solidcraft_engine::render::job::Phase; + use std::{sync::mpsc, time::Duration}; + // The actual capture thread owns and invokes the real engine Snapshot.run. + // This test only withholds its actual returned message from the UI consumer. + // No tick/paint is called while the receiver is temporarily removed. + let mut pending = h.app.render_workspace.interactive.pending.take().expect("production tick must start a capture"); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).expect("real snapshot worker did not return"); + assert!(matches!(&reply, Ok(true)), "real snapshot must be adopted: {reply:?}"); + let job = + interactive::test_current(&h.app).expect("Interactive controller access must succeed").expect("Snapshot.run must attach the real CPU job"); + assert_eq!(job.id(), pending.ticket.job_id()); + assert_eq!(pending.uid, h.app.session.uid); + let status = job.wait_timeout(Duration::from_secs(60)).expect("real CPU job did not finish"); + assert_eq!(status.progress.phase, Phase::Completed); + assert!(status.error.is_none()); + assert_eq!(status.request.integrator, Integrator::Raytrace); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive.unwrap().samples_per_pixel, 16); + assert_eq!((status.request.width, status.request.height), (16, 16)); + let frame = job.frame().unwrap().expect("Completed requires real frame bytes"); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert_eq!(frame.info.job, job.id()); + assert_eq!(frame.info.scene_generation, pending.ticket.revision().scene_generation); + assert!(!frame.png().is_empty()); + assert_eq!(frame.info.png_bytes, frame.png().len() as u64); + { + use sha2::{Digest, Sha256}; + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + } + assert!(job.preview().unwrap().is_none(), "terminal image is distinct from the intermediate preview slot"); + // The renderer's Completed progress is normalized to 1/1, not an SPP counter. + assert_eq!((status.progress.done, status.progress.total), (1, 1)); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + InteractiveHeldCallback { job, sender, reply } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_assert_final_export_isolation(h: &mut Harness, job: &solidcraft_engine::render::job::JobHandle) { + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.render_workspace.image.is_none()); + assert!(!studio::linear_export_available(&h.app)); + let registry_error = h.app.session.render_job_handle(job.id()).err().expect("preview must not enter the final registry"); + assert!(registry_error.to_string().contains("WrongOwner"), "{registry_error}"); + let path = h.dir.join(format!("interactive-not-exportable-{}-{}.png", job.id().session, job.id().serial)); + assert!(!path.exists()); + let error = h.app.session.execute("render.export", &json!({"job":job.id(),"path":path,"format":"png"})).unwrap_err(); + // Require the actual preview/final ownership guard, rather than accepting a + // path/format/refusal error which would not prove final-registry isolation. + assert!(error.to_string().contains("WrongOwner"), "{error}"); + assert!(!path.exists()); + assert!(job.frame().unwrap().is_some(), "export refusal must not consume preview pixels"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_snapshot_worker_cpu16_png_is_cached_painted_reused_and_never_final_exported() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_snapshot_worker_cpu16_png_is_cached_painted_reused_and_never_final_exported") { + return; + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + assert!(!h.app.render_workspace.interactive.pending()); + // Explicit egui time relative to the inherited clock crosses the 200 ms group; + // this does not wait on wall time or sleep to make a race likely. + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + assert!(interactive::test_cache(&h.app).is_none(), "worker completion alone must not fabricate a UI cache"); + let frame = held.job.frame().unwrap().unwrap(); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + assert!(!h.app.render_workspace.interactive.pending()); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(cached.job, held.job.id()); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + assert_eq!(samples, 16); + assert!(complete, "completed16 must use the completed key, still only in the provisional UI cache"); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + assert_eq!(interactive::inspect(&h.app)["stale"], false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + let uploaded = &output.textures_delta.set.get(&texture).expect("first real PNG publication must upload a texture").first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [png.width() as usize, png.height() as usize]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + output.textures_delta.clear(); + assert!( + h.ctx + .tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == texture && !mesh.indices.is_empty())) + ); + let (mut repaint, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(painted); + assert_eq!(interactive::test_cache(&h.app).unwrap().3, texture); + assert!(!repaint.textures_delta.set.contains_key(&texture), "unchanged JobId/sequence/revision must reuse its texture"); + repaint.textures_delta.clear(); + interactive_assert_final_export_isolation(&mut h, &held.job); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_off_and_reenable_cannot_fill_new_cache_or_spawn_twice() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_off_and_reenable_cannot_fill_new_cache_or_spawn_twice") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(h.app.render_workspace.interactive.pending(), "Off retains the single undrained receiver"); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 1.0, true); + let pending = h.app.render_workspace.interactive.pending.as_ref().unwrap(); + assert_eq!(pending.ticket.job_id(), held.job.id(), "reactivation cannot replace an undrained capture"); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 1.1, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_pause_cannot_publish_unseen_old_pixels() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_pause_cannot_publish_unseen_old_pixels") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(h.app.render_workspace.interactive.pending()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(!painted, "Pause may retain already displayed pixels, but cannot adopt this unseen callback"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_camera_edit_is_discarded_then_new_capture_can_publish() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_camera_edit_is_discarded_then_new_capture_can_publish") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let old = held.job.id(); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let revision = h.app.session.revision; + h.app.cam.yaw += 0.2; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert_eq!(h.app.session.revision, revision); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + interactive_clear_acceptance_frame(&mut h, epoch + 0.501, true); + let newer = interactive_hold_real_completed_callback(&mut h); + assert_ne!(newer.job.id(), old); + newer.sender.send(newer.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.6, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, newer.job.id()); + assert_eq!(interactive::inspect(&h.app)["samples"], 16); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + interactive_assert_final_export_isolation(&mut h, &newer.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +struct InteractiveRecoveryReply { + id: solidcraft_engine::render::job::JobId, + sender: std::sync::mpsc::Sender>, + reply: Result, +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_hold_reply(h: &mut Harness) -> InteractiveRecoveryReply { + use std::{sync::mpsc, time::Duration}; + let mut pending = h.app.render_workspace.interactive.pending.take().expect("actual tick must dispatch a Snapshot"); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).expect("actual capture worker did not return"); + let id = pending.ticket.job_id(); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + InteractiveRecoveryReply { id, sender, reply } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_missing_hdr(h: &mut Harness) -> (std::path::PathBuf, Vec) { + let path = h.dir.join("interactive-recovery-original.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + assert!(interactive_request(&h.app).is_ok(), "valid inspected metadata must reach actual worker preparation"); + std::fs::remove_file(&path).unwrap(); + (path, bytes) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_require_error(h: &mut Harness, time: f64) -> serde_json::Value { + interactive_clear_acceptance_frame(h, time, true); + let status = interactive::inspect(&h.app); + assert_eq!(status["phase"], "Error"); + assert!(status["error"].as_str().is_some_and(|error| !error.is_empty())); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + status["error"].clone() +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_require_success(h: &mut Harness, dispatch_time: f64, paint_time: f64) -> solidcraft_engine::render::job::JobId { + interactive_clear_acceptance_frame(h, dispatch_time, true); + let held = interactive_hold_real_completed_callback(h); + let id = held.job.id(); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(h, paint_time, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["samples"], 16); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, id); + interactive_assert_final_export_isolation(h, &held.job); + id +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_invalid_hdr_selection_never_dispatches_and_input_edit_can_recover() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_invalid_hdr_selection_never_dispatches_and_input_edit_can_recover") { + return; + } + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: h.dir.join("not-inspected.hdr").to_string_lossy().into_owned() }; + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 2.0), error); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 2.1, false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_recovery_require_success(&mut h, epoch + 2.301, epoch + 2.4); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_hdr_file_error_latches_until_same_intent_resume_or_actual_input_edit() { + for recovery in ["resume", "edit"] { + let mut h = interactive_ui_fixture(); + let case = format!("interactive_real_hdr_file_error_latches_until_same_intent_resume_or_actual_input_edit:{recovery}"); + if !interactive_test_cpu_branch(&mut h, &case) { + continue; + } + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let request = interactive_request(&h.app).unwrap(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.as_ref().is_err_and(|error| !error.is_empty()), "missing HDR must fail actual preparation: {:?}", failed.reply); + assert!( + interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none(), + "preparation failure is not an admitted job-status failure" + ); + let failed_id = failed.id; + failed.sender.send(failed.reply).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + for offset in [0.6, 1.0] { + assert_eq!(interactive_recovery_require_error(&mut h, epoch + offset), error, "unchanged input must not retry"); + } + if recovery == "resume" { + std::fs::write(&path, bytes).unwrap(); + assert_eq!(interactive_request(&h.app).unwrap(), request, "repairing external bytes is not a UI intent edit"); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.1), error, "file repair alone cannot silently resume"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + } else { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + } + let new_id = interactive_recovery_require_success(&mut h, epoch + 1.301, epoch + 1.4); + assert_ne!(new_id, failed_id); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_user_pause_survives_error_fixing_edit_until_explicit_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_user_pause_survives_error_fixing_edit_until_explicit_resume") { + return; + } + let _ = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + failed.sender.send(failed.reply).unwrap(); + interactive_recovery_require_error(&mut h, epoch + 0.3); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 0.4, false); + interactive_clear_acceptance_frame(&mut h, epoch + 2.0, true); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 2.201, epoch + 2.3); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_disconnected_real_callback_transport_latches_and_resume_creates_fresh_capture() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_disconnected_real_callback_transport_latches_and_resume_creates_fresh_capture") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + assert!(held.reply.unwrap(), "native Snapshot/CPU work really finished before transport failure"); + // Deliberately close the actual std channel instead of fabricating an Err. + // This covers consumer Disconnected, not a claim that the native worker crashed. + drop(held.sender); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + assert_eq!(error, h.app.tr("render.interactive_error")); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let newer = interactive_recovery_require_success(&mut h, epoch + 1.201, epoch + 1.3); + assert_ne!(newer, held.job.id()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_late_real_preparation_error_cannot_overwrite_edited_or_resumed_intent() { + for recovery in ["edit", "resume"] { + let mut h = interactive_ui_fixture(); + let case = format!("interactive_late_real_preparation_error_cannot_overwrite_edited_or_resumed_intent:{recovery}"); + if !interactive_test_cpu_branch(&mut h, &case) { + continue; + } + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + if recovery == "edit" { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + } else { + std::fs::write(path, bytes).unwrap(); + // First consume clock input without consuming the still-held reply. + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + } + interactive_clear_acceptance_frame(&mut h, epoch + 0.501, true); + assert_eq!( + h.app.render_workspace.interactive.pending.as_ref().unwrap().ticket.job_id(), + failed.id, + "one old receiver still blocks new dispatch" + ); + failed.sender.send(failed.reply).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.6, false); + assert!(interactive::inspect(&h.app)["error"].is_null(), "actual old failure must be discarded"); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + let new_id = interactive_recovery_require_success(&mut h, epoch + 0.7, epoch + 0.8); + assert_ne!(new_id, failed.id); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_final_priority_never_clears_a_latched_error_or_retries_without_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_final_priority_never_clears_a_latched_error_or_retries_without_resume") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + failed.sender.send(failed.reply).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + let final_job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + let id = serde_json::from_value(reply["job"].clone()).unwrap(); + background.session.render_job_handle(id).unwrap() + }; + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 0.4), error); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).unwrap_err().contains(h.app.tr("render.interactive_final_active"))); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + // Only the test's explicit owner cancellation ends its queued final. + final_job.cancel().unwrap(); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 0.5), error); + std::fs::write(path, bytes).unwrap(); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.701, epoch + 0.8); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Cancelled); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_actual_png_display_cap_error_latches_until_explicit_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_actual_png_display_cap_error_latches_until_explicit_resume") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + held.sender.send(held.reply).unwrap(); + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.3), + ..Default::default() + }, + |ui| { + // Real decoder admission against an invalid display capability; retain + // the real CPU PNG and restore input before fonts/end-frame processing. + let previous = ui.ctx().input(|input| input.max_texture_side); + ui.ctx().input_mut(|input| input.max_texture_side = 0); + interactive::before_paint(&mut h.app, ui.ctx()); + ui.ctx().input_mut(|input| input.max_texture_side = previous); + assert!(!interactive::paint(&h.app, ui, ui.max_rect())); + }, + ); + output.textures_delta.clear(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.4); + assert_eq!(error, h.app.tr("render.error_display_dimensions")); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error, "restoring display cap alone cannot rearm capture"); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let newer = interactive_recovery_require_success(&mut h, epoch + 1.201, epoch + 1.3); + assert_ne!(newer, held.job.id()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_card_dimensions_use_real_paused_preview_not_changed_final_draft() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_card_dimensions_use_real_paused_preview_not_changed_final_draft") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.4), + ..Default::default() + }, + |ui| { + interactive::before_paint(&mut h.app, ui.ctx()); + interactive::controls(&mut h.app, ui); + }, + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + assert!(text.contains("16 × 16 px"), "actual cached dimensions must be visible: {text}"); + assert!(!text.contains("3840 × 2160 px"), "final draft cannot relabel the captured preview"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + let (info, samples, complete, _) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((info.width, info.height, samples, complete), (16, 16, 16, true)); + output.textures_delta.clear(); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn interactive_card_bounds_avoid_current_selection_docks_and_navigation_at_wide_and_narrow_sizes() { + for (width, height) in [(1600.0, 1000.0), (760.0, 700.0)] { + let mut h = Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.shell.workspace_panels.clear(); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); + let content = egui::Rect::from_min_max(egui::pos2(0.0, 132.0), egui::pos2(width, height - 56.0)); + let left = egui::Rect::from_min_max(egui::pos2(8.0, 140.0), egui::pos2(274.0, height - 64.0)); + let right = egui::Rect::from_min_max(egui::pos2(width - 313.0, 140.0), egui::pos2(width - 8.0, height - 64.0)); + crate::shell::register_panel(&mut h.app, "render:browser", Some(left), Some(crate::ui_kit::Edge::Left)); + crate::shell::register_panel(&mut h.app, "render:inspector", Some(right), Some(crate::ui_kit::Edge::Right)); + let centre = (left.right() + right.left()) / 2.0; + let navigation = egui::Rect::from_center_size(egui::pos2(centre, content.bottom() - 28.0), egui::vec2(120.0, 40.0)); + let axis = egui::Rect::from_min_size(egui::pos2(right.left() - 110.0, content.top()), egui::vec2(110.0, 110.0)); + h.app.viewport.layout = + Some(crate::viewport_layout::Layout { viewport, drawable: content, content, axis_view: axis, navigation, confirm: egui::Rect::NOTHING }); + // A new measured selection replaces the old one in this very frame. + // Both positions cut across the old top-centre status/action region. + for y in [content.top() + 90.0, content.top() + 180.0] { + let selection = egui::Rect::from_center_size(egui::pos2(centre, y), egui::vec2(180.0, 34.0)); + crate::shell::register_panel(&mut h.app, "render:selection", Some(selection), None); + let available = interactive::overlay_bounds(&h.app, content); + assert!(available.is_positive(), "{width}: no space for the Interactive card"); + assert!(content.contains_rect(available), "{width}: {available:?} outside {content:?}"); + for occupied in [selection, left, right, navigation, axis] { + assert!(!available.intersect(occupied).is_positive(), "{width}: {available:?} overlaps {occupied:?}"); + } + assert!(available.width() >= Tokens::get().control_height + Tokens::get().space_8); + } + assert!(!interactive::overlay_bounds(&h.app, egui::Rect::NOTHING).is_positive()); + assert_eq!(h.app.shell.workspace_panels["render:browser"].0, left); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0, right); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_overlay_keeps_real_selection_actions_and_pause_off_targets_accessible_without_dispatch() { + fn overlay_frame(h: &mut Harness, size: egui::Vec2, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }, + |ui| { + // The shell clears Render reservations at the start of a real frame. + // Keep the already measured docks but never leave a previous selection + // rectangle that could make the moved-call regression pass by accident. + h.app.shell.workspace_panels.remove("render:selection"); + crate::render_ui::overlays(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); + } + for size in [egui::vec2(1600.0, 1000.0), egui::vec2(760.0, 700.0)] { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_overlay_selection_controls") { + return; + } + h.call("ui.resize", json!({"width":size.x as u32,"height":size.y as u32})); + h.app.run("appearance.assign", json!({"bodies":["Subject"],"appearance":"ABS - Blue"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Subject".into()}]})).unwrap(); + h.frames(4); + for _ in 0..3 { + overlay_frame(&mut h, size, vec![]); + } + let selection_before = crate::scenario::rect_of("render:selection").unwrap(); + let actions_before: Vec<_> = (0..4).map(|index| crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap()).collect(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let docks = h.app.shell.workspace_panels.clone(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + // Paint the production overlays, but never tick or run a Snapshot worker. + for _ in 0..3 { + overlay_frame(&mut h, size, vec![]); + } + let card = crate::scenario::rect_of("render:interactive-card").unwrap(); + let selection = crate::scenario::rect_of("render:selection").unwrap(); + assert_eq!(selection, selection_before, "our card must not move the author's toolbar"); + assert!(!card.intersect(selection).is_positive()); + let content = crate::render_ui::canvas(&h.app, h.app.viewport.rect.unwrap()); + assert!(content.contains_rect(card), "{size:?}: {card:?} outside {content:?}"); + for (index, before) in actions_before.iter().enumerate() { + let action = crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap(); + assert_eq!(&action, before); + assert!(selection.contains_rect(action)); + assert!(!card.intersect(action).is_positive(), "author action {index} is occluded"); + } + for action in ["pause", "off"] { + let target = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap(); + assert!(card.contains_rect(target), "{size:?}: {action} clipped outside {card:?}: {target:?}"); + assert!(!selection.intersect(target).is_positive()); + } + for action in ["pause", "off"] { + let at = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap().center(); + for pressed in [true, false] { + overlay_frame( + &mut h, + size, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + overlay_frame(&mut h, size, vec![]); + assert_eq!(interactive::inspect(&h.app)["paused"], action == "pause"); + assert_eq!(interactive::inspect(&h.app)["enabled"], action != "off"); + assert!(!h.app.render_workspace.interactive.pending()); + } + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + for id in ["render:browser", "render:inspector", "render:appearances", "render:shots_strip"] { + let current = h.app.shell.workspace_panels.get(id).map(|(rect, edge)| (*rect, edge.as_ref().map(std::mem::discriminant))); + let before = docks.get(id).map(|(rect, edge)| (*rect, edge.as_ref().map(std::mem::discriminant))); + assert_eq!(current, before, "{id}"); + } + // With Interactive Off, the author's real hit target still dispatches. + let favorite_count = h.app.preferences.render_library_favorites.len(); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert_eq!(h.app.preferences.render_library_favorites.len(), favorite_count + 1); + assert_eq!(crate::scenario::rect_of("render:selection").unwrap(), selection_before); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_waiting_show_text(h: &mut Harness, time: f64) -> String { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), + time: Some(time), + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + output.textures_delta.clear(); + text +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_uses_real_show_and_keeps_off_pause_error_and_result_routes() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_uses_real_show_and_keeps_off_pause_error_and_result_routes") { + return; + } + assert!(h.app.viewport.gpu.is_none(), "the fallback refusal is the real no-GPU positive control"); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + let fallback = h.app.tr("render.error_gpu_preview").to_string(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.01).contains(&fallback)); + + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let waiting = interactive_waiting_show_text(&mut h, epoch + 0.02); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!waiting.contains(&fallback), "real show must not enter the model-preview refusal while waiting"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "show/before_paint must not dispatch"); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.025, false, true); + assert!(!painted, "reserving the canvas does not claim an image was painted"); + output.textures_delta.clear(); + + h.app.render_workspace.view.result = true; + assert!(!interactive::awaiting_current_frame(&h.app), "the result view keeps priority"); + h.app.render_workspace.view.result = false; + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(!interactive::awaiting_current_frame(&h.app)); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.ui.tab = "MODEL".into(); + assert!(!interactive::awaiting_current_frame(&h.app)); + h.app.ui.tab = "RENDER".into(); + + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.03).contains(&fallback), "pause before any image keeps its existing fallback"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + assert!(!interactive_waiting_show_text(&mut h, epoch + 0.04).contains(&fallback)); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: h.dir.join("not-inspected.hdr").to_string_lossy().into_owned() }; + let error = interactive_waiting_show_text(&mut h, epoch + 0.05); + assert_eq!(interactive::inspect(&h.app)["phase"], "Error"); + assert!(!interactive::inspect(&h.app)["error"].is_null()); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(error.contains(&fallback), "an input error keeps the existing model-preview route"); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.06).contains(&fallback)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_after_supported_edit_drops_old_pixels_and_new_capture_still_publishes() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_after_supported_edit_drops_old_pixels_and_new_capture_still_publishes") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.render_workspace.view.raytrace.shadows = true; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let old = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + assert!(!interactive::awaiting_current_frame(&h.app)); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let document = h.app.session.doc.clone(); + + h.app.render_workspace.view.raytrace.shadows = false; + let text = interactive_waiting_show_text(&mut h, epoch + 0.4); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::test_cache(&h.app).is_none(), "the previously accepted image must be dropped"); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.41, false, true); + assert!(!painted, "old pixels cannot become current while the new request waits"); + output.textures_delta.clear(); + + let new = interactive_recovery_require_success(&mut h, epoch + 0.901, epoch + 1.0); + assert_ne!(new, old); + assert!(!interactive::awaiting_current_frame(&h.app)); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), new); + assert!(!job.status().unwrap().request.raytrace.as_ref().unwrap().shadows); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "presentation and runtime settings do not author CAD state"); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_preserves_paused_out_of_date_pixels_and_resume_waits_without_fallback() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_preserves_paused_out_of_date_pixels_and_resume_waits_without_fallback") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.render_workspace.view.raytrace.shadows = true; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let (before, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.raytrace.shadows = false; + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(painted, "explicit pause still permits the already displayed image"); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert!(!interactive::awaiting_current_frame(&h.app)); + let (after, after_samples, after_complete, after_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((after.job, after.png_sha256), (before.job, before.png_sha256)); + assert_eq!((after_samples, after_complete, after_texture), (samples, complete, texture)); + + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let text = interactive_waiting_show_text(&mut h, epoch + 0.5); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.51, false, true); + assert!(!painted); + output.textures_delta.clear(); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_camera_late_callback_and_document_switch_never_adopt_old_pixels() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_camera_late_callback_and_document_switch_never_adopt_old_pixels") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.cam.yaw += 0.2; + let text = interactive_waiting_show_text(&mut h, epoch + 0.3); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::awaiting_current_frame(&h.app)); + interactive_assert_final_export_isolation(&mut h, &held.job); + + let old_uid = h.app.session.uid; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_ne!(h.app.session.uid, old_uid); + assert!(!interactive::awaiting_current_frame(&h.app), "a foreign context cannot reserve the canvas even before refresh"); + h.app.ui.tab = "RENDER".into(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.5, false); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.6, false, true); + assert!(!painted, "neither the old image nor its waiting presentation belongs to another document"); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_rejects_live_foreign_session_without_resetting_context() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_rejects_live_foreign_session_without_resetting_context") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + assert!(interactive::awaiting_current_frame(&h.app)); + let before = interactive::inspect(&h.app); + assert_eq!(before["enabled"], true); + assert_eq!(before["phase"], "Updating"); + assert_eq!(before["paused"], false); + assert!(before["error"].is_null()); + assert!(!h.app.render_workspace.view.result); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + + let uid = h.app.session.uid; + let document = h.app.session.doc.clone(); + let mut foreign = Session::new((*document).clone()); + assert_ne!(foreign.uid, uid); + // Use real engine Sessions and the same ownership swap as documents::swap_in. + // Deliberately omit the UI reset: it would otherwise mask is_current's guard. + // Retain the original Session so its registry/controller lifetime stays live. + std::mem::swap(&mut h.app.session, &mut foreign); + assert_ne!(h.app.session.uid, uid); + assert_eq!(h.app.session.doc, document, "equal design contents do not confer session ownership"); + assert_eq!(interactive::inspect(&h.app), before, "the context is still enabled, not reset or refreshed"); + assert!(active(&h.app)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(!h.app.render_workspace.view.result); + assert!(!interactive::awaiting_current_frame(&h.app), "a live context owned by another Session cannot reserve the canvas"); + assert_eq!(interactive::inspect(&h.app), before, "the predicate must remain read-only"); + + std::mem::swap(&mut h.app.session, &mut foreign); + assert_eq!(h.app.session.uid, uid); + assert_eq!(interactive::inspect(&h.app), before); + assert!(interactive::awaiting_current_frame(&h.app), "restoring the real owner proves the same context remained live"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!h.app.render_workspace.interactive.pending()); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_frame(h: &mut Harness, time: &mut f64, events: Vec) { + *time += 1.0 / 60.0; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), + time: Some(*time), + focused: true, + events, + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + output.textures_delta.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_fixture(case: &str) -> Option<(Harness, f64, egui::Pos2)> { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, case) { + return None; + } + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + h.app.preferences.nav = "fusion".into(); + h.app.preferences.zoom_to_cursor = false; + h.app.preferences.smooth_wheel_zoom = false; + let mut time = interactive::test_clock(&h.app).as_secs_f64(); + for _ in 0..3 { + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + } + let rect = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, rect); + let at = projection.to_screen(h.app.cam.target).unwrap(); + assert!(!crate::shell::covered(&h.app, at)); + assert!( + crate::viewport::pick(&h.app, &projection, at).iter().any(|hit| matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject")) + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + Some((h, time, at)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_click(h: &mut Harness, time: &mut f64, at: egui::Pos2, button: egui::PointerButton, mods: egui::Modifiers) { + interactive_canvas_input_frame(h, time, vec![egui::Event::ModifiersChanged(mods), egui::Event::PointerMoved(at)]); + for pressed in [true, false] { + interactive_canvas_input_frame(h, time, vec![egui::Event::PointerButton { pos: at, button, pressed, modifiers: mods }]); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_blocks_hover_selection_and_context_but_off_keeps_real_targets() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_blocks_hover_selection_and_context_but_off_keeps_real_targets") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL] { + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, mods); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(h.app.viewport.hover.is_none(), "hidden geometry cannot advertise a hover target"); + assert!(h.app.session.selection.is_empty(), "plain/add/toggle clicks cannot select invisible geometry"); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none(), "a right click cannot open a menu for hidden geometry"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.render_workspace.interactive.pending(), "show never dispatches a capture"); + + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_some(), "the same real hit remains available with Interactive Off"); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_some(), "the same native canvas click still opens the normal body menu"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_neither_paints_nor_samples_and_escape_and_off_still_work() { + for sampling in [false, true] { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_neither_paints_nor_samples_and_escape_and_off_still_work") + else { + return; + }; + if sampling { + h.app.start("appearance.pick_up"); + } else { + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let look = h.app.render_workspace.view.assign.look.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.render_workspace.view.assign.look, look, "no hidden face is sampled"); + assert_eq!(h.app.render_workspace.view.assign.sampling, sampling); + assert_eq!(h.app.render_workspace.view.assign.painting, !sampling); + + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + if sampling { + h.app.start("appearance.pick_up"); + } else { + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + if sampling { + assert!(!h.app.render_workspace.view.assign.sampling); + assert!(h.app.render_workspace.view.assign.painting, "Off permits real sampling to arm paint"); + } else { + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies.get("Subject").unwrap().name, "ABS - Blue"); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_clears_real_drag_preview_and_release_cannot_apply_hidden_target() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_clears_real_drag_preview_and_release_cannot_apply_hidden_target") + else { + return; + }; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "positive control: real Off drag reached geometry"); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(assign::preview(&h.app).is_none()); + assert!(assign::hover(&h.app).is_none()); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_current_and_paused_images_keep_canvas_paint_and_final_observation() { + for paused in [false, true] { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_current_and_paused_images_keep_canvas_paint_and_final_observation") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + if paused { + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + let undo = h.app.session.undo.len(); + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies.get("Subject").unwrap().name, "ABS - Blue"); + if paused { + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!interactive::awaiting_current_frame(&h.app)); + } else { + assert!(interactive::test_cache(&h.app).is_none(), "the final observation sees the appearance edit made by this canvas click"); + assert!(interactive::awaiting_current_frame(&h.app)); + } + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_canvas_reobserves_pending_edit_before_release_and_navigation_still_updates_camera() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_canvas_reobserves_pending_edit_before_release_and_navigation_still_updates_camera") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + assert!(interactive::test_cache(&h.app).is_some(), "before show, old UI state has not yet observed the visible setting edit"); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(h.app.session.selection.is_empty(), "the release cannot pick using the previous frame's cache/phase"); + assert!(h.app.viewport.hover.is_none()); + + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, 3.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }], + ); + assert_ne!(h.app.cam, camera, "the waiting guard must not swallow real shared camera navigation"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(h.app.viewport.hover.is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "neither observation dispatches Snapshot"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_accepted_image_drag_setting_edit_and_immediate_release_never_applies_hidden_target() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_accepted_image_drag_setting_edit_and_immediate_release_never_applies_hidden_target") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + let (accepted, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(accepted.job, job); + assert_eq!((samples, complete), (16, true)); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(!h.app.render_workspace.interactive.pending()); + + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let selection = h.app.session.selection.clone(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "the real drag must start over the accepted CPU image"); + assert!(assign::hover(&h.app).is_some()); + let (pressed, pressed_samples, pressed_complete, pressed_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((pressed.job, &pressed.png_sha256), (job, &accepted.png_sha256)); + assert_eq!((pressed_samples, pressed_complete, pressed_texture), (samples, complete, texture)); + assert!(!interactive::awaiting_current_frame(&h.app)); + + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + // No tick, show, refresh, move or other UI frame between this edit and release. + // The old image/drag are still present, so only same-frame observation can reject the drop. + let (before_release, _, _, before_release_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((before_release.job, &before_release.png_sha256, before_release_texture), (job, &accepted.png_sha256, texture)); + assert!(assign::preview(&h.app).is_some()); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(assign::preview(&h.app).is_none()); + assert!(assign::hover(&h.app).is_none()); + assert!(h.app.viewport.hover.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert_eq!(h.app.session.selection, selection); + assert!(!h.app.render_workspace.interactive.pending(), "show must not dispatch Snapshot to consume this release"); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "show must not attach a replacement CPU job"); + assert!(active(&h.app)); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(!assign::cancel(&mut h.app), "the release must consume the drag; nothing may remain for Escape to cancel"); + + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(assign::preview(&h.app).is_none() && assign::hover(&h.app).is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_clicks_preserve_selection_created_on_the_accepted_image() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_clicks_preserve_selection_created_on_the_accepted_image") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + assert!(!interactive::awaiting_current_frame(&h.app)); + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL] { + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, mods); + assert_eq!(h.app.session.selection, selection, "blank-canvas clicks cannot clear, add to or toggle the existing selection"); + assert!(h.app.viewport.hover.is_none()); + assert!(interactive::awaiting_current_frame(&h.app)); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn gpu_failed_host_keeps_specific_reason_in_image_params_and_disabled_commands() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for reason in ["This Direct3D 12 session has not tested Vulkan.", "Vulkan device creation failed: deliberate independent diagnostic 47."] { + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + assert_ne!(reason, h.app.tr("render.gpu_unavailable")); + assert_eq!(image_params(&h.app).unwrap_err(), reason); + for id in ["render.preflight", "render.start"] { + let command = solidcraft_engine::find_command(id).unwrap(); + assert!(command.info(&h.app.session).enabled, "the engine must not hide the UI readiness check"); + let info = interactive_command_info(&h.app, command); + assert!(!info.enabled, "{id}"); + assert_eq!(info.disabled_reason.as_deref(), Some(reason), "{id}"); + } + assert!(matches!(&h.app.render_workspace.path_host, PathHost::Failed(stored) if stored == reason)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn gpu_pending_hosts_keep_generic_disabled_reason_without_starting_setup() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let generic = h.app.tr("render.gpu_unavailable").to_string(); + // This channel represents a still-pending answer; no worker or GPU factory is created. + let (_sender, receiver) = std::sync::mpsc::channel(); + for host in [PathHost::NotStarted, PathHost::Preparing(receiver, std::time::Instant::now())] { + let preparing = matches!(&host, PathHost::Preparing(..)); + h.app.render_workspace.path_host = host; + assert_eq!(image_params(&h.app).unwrap_err(), generic); + for id in ["render.preflight", "render.start"] { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert!(!info.enabled, "{id}"); + assert_eq!(info.disabled_reason.as_deref(), Some(generic.as_str()), "{id}"); + } + assert_eq!(matches!(&h.app.render_workspace.path_host, PathHost::Preparing(..)), preparing); + assert!(matches!(&h.app.render_workspace.path_host, PathHost::NotStarted | PathHost::Preparing(..))); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn gpu_failed_host_preserves_raster_readiness_and_cooperative_cpu_refusal() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":12,"height":3})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.image_host = Some(solidcraft_engine::render::job::CpuHost::cooperative()); + sync_backend(&mut h.app); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + h.app.render_workspace.view.method = method; + h.app.render_workspace.path_host = PathHost::NotStarted; + let baseline = image_params(&h.app); + if method == ImageMethod::Raster { + assert!(baseline.is_ok(), "cooperative Raster must be available: {baseline:?}"); + } else { + assert_eq!(method, ImageMethod::CpuRaytrace); + let error = baseline.as_ref().unwrap_err(); + assert!(error.contains("CPU raytracing"), "cooperative CPU must retain its own host refusal: {error}"); + assert_ne!(error, h.app.tr("render.gpu_unavailable")); + } + let baseline_commands = ["render.preflight", "render.start"].map(|id| { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert_eq!(info.enabled, method == ImageMethod::Raster, "{method:?}: {id}"); + assert_eq!(info.disabled_reason.as_deref(), baseline.as_ref().err().map(String::as_str), "{method:?}: {id}"); + (id, info.enabled, info.disabled_reason) + }); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let reason = "Deliberate GPU-only refusal must not replace another method's readiness."; + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + assert_eq!(image_params(&h.app), baseline, "{method:?}: preserve the exact success or rejection"); + for (id, enabled, disabled_reason) in baseline_commands { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert_eq!(info.enabled, enabled, "{method:?}: {id}"); + assert_eq!(info.disabled_reason, disabled_reason, "{method:?}: {id}"); + } + assert!(matches!(&h.app.render_workspace.path_host, PathHost::Failed(stored) if stored == reason)); + assert_eq!(h.app.render_workspace.view.method, method); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_area_and_led_real_snapshot_pixels_reach_receiver_cache_without_final_export() { + use solidcraft_engine::render::job::{RectangleLightOptions, led_strip::LedStripOptions}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_area_and_led_real_snapshot_pixels_reach_receiver_cache_without_final_export") { + return; + } + h.app.render_workspace.view.raytrace.area_lights = Some(vec![RectangleLightOptions { + center_mm: [5.0, 4.0, 20.0], + edge_u_mm: [4.0, 0.0, 0.0], + edge_v_mm: [0.0, -4.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]); + h.app.render_workspace.view.raytrace.area_samples = Some(4); + h.app.render_workspace.view.raytrace.seed = Some(73); + LedStripOptions { + center_mm: [5.0, 4.0, 12.0], + length_mm: 8.0, + width_mm: 1.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [0.25, 0.5, 1.0], + intensity: 3.0, + } + .append_to(&mut h.app.render_workspace.view.raytrace, 4) + .unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 0.75; + let expected = h.app.render_workspace.view.raytrace.area_lights.clone().unwrap(); + assert_eq!(expected.len(), 2); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + // Existing helper dispatches the real Snapshot, receives its real reply, + // validates real native PNG bytes/hash, drains the reply and paints the cache. + let id = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), id); + let status = job.status().unwrap(); + let options = status.request.raytrace.as_ref().unwrap(); + assert_eq!(options.area_lights.as_ref(), Some(&expected)); + assert_eq!(options.area_samples, Some(4)); + assert_eq!(options.seed, Some(73)); + assert_eq!(options.exposure_ev, 0.75); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + let (cached, samples, complete, _) = interactive::test_cache(&h.app).unwrap(); + let frame = job.frame().unwrap().unwrap(); + assert_eq!((cached.job, cached.png_sha256), (id, frame.info.png_sha256.clone())); + assert_eq!((cached.width, cached.height, samples, complete), (16, 16, 16, true)); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_led_light_edit_and_final_preemption_discard_real_late_replies_without_erasing_final() { + use solidcraft_engine::render::job::{CpuHost, JobId, Phase, led_strip::LedStripOptions}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_led_light_edit_and_final_preemption_discard_real_late_replies_without_erasing_final") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + LedStripOptions { + center_mm: [5.0, 4.0, 12.0], + length_mm: 8.0, + width_mm: 1.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + } + .append_to(&mut h.app.render_workspace.view.raytrace, 4) + .unwrap(); + h.app.render_workspace.view.raytrace.seed = Some(91); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let first = interactive_hold_real_completed_callback(&mut h); + let old = first.job.id(); + let old_options = first.job.status().unwrap().request.raytrace.unwrap(); + assert_eq!(old_options.area_lights.as_ref().unwrap().first().unwrap().intensity, 2.0); + assert_eq!((old_options.area_samples, old_options.seed), (Some(4), Some(91))); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.area_lights.as_mut().unwrap().first_mut().unwrap().intensity = 1.5; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "light edit must detach the old owned job"); + first.sender.send(first.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &first.job); + + interactive_clear_acceptance_frame(&mut h, epoch + 0.601, true); + let second = interactive_hold_real_completed_callback(&mut h); + assert_ne!(second.job.id(), old); + let new_options = second.job.status().unwrap().request.raytrace.unwrap(); + assert_eq!(new_options.area_lights.as_ref().unwrap().first().unwrap().intensity, 1.5); + assert_eq!((new_options.area_samples, new_options.seed), (Some(4), Some(91))); + let final_host = CpuHost::cooperative(); + let final_job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(final_host.clone())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + background.session.render_job_handle(id).unwrap() + }; + let retained = final_host.admitted_bytes(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.7, false); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + second.sender.send(second.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.8, false, true); + assert!(!painted, "a final-suspended late LED reply cannot fill the preview cache"); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &second.job); + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued); + assert_eq!(final_host.admitted_bytes(), retained); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued, "Off cannot cancel the unrelated final"); + final_job.cancel().unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle() { + use solidcraft_engine::render::job::DirectionalLightOptions; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle") { + return; + } + h.app + .run( + "appearance.assign", + json!({"bodies":["Subject"],"color":"#808080","opacity":1.0, + "pbr":{"metallic":0.0,"roughness":1.0,"dielectric_ior":1.0}}), + ) + .unwrap(); + // Front view sees the y=0 face normally. All jittered rays through the + // central pixel stay inside that face, so neither coverage nor noise is an oracle. + h.app.cam.target = solidcraft_engine::geom::Vec3::new(5.0, 4.0, 2.0); + h.app.cam.yaw = 0.0; + h.app.cam.pitch = 0.0; + h.app.cam.roll = 0.0; + h.app.cam.distance = 10.0; + h.app.cam.fov = 0.0; + h.app.cam.up = solidcraft_engine::render::UpAxis::Z; + h.app.render_workspace.view.cpu.environment = cpu::Environment::None; + h.app.render_workspace.view.raytrace = solidcraft_engine::render::job::RaytraceOptions { + lights: Some(vec![DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 0.5 }]), + shadows: false, + ..Default::default() + }; + let camera = h.app.cam; + let final_options = h.app.render_workspace.view.raytrace.clone(); + let final_size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let mut previous_job = None; + let mut baseline_png = None; + let mut previous_visual = None; + for (step, ev) in [0.0_f64, 1.0, -1.0, 0.0].into_iter().enumerate() { + let time = epoch + step as f64; + h.app.render_workspace.view.draft.exposure_ev = ev; + interactive_clear_acceptance_frame(&mut h, time, false); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + if let Some(previous) = previous_visual { + assert!(visual > previous, "each committed EV must invalidate the previous image"); + } + previous_visual = Some(visual); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + // This is the real runtime request, not a test-only renderer request. + let wire = interactive_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["exposure_ev"], 0.0, "outer EV must not duplicate the CPU EV"); + assert_eq!(wire["raytrace"]["exposure_ev"], ev); + interactive_clear_acceptance_frame(&mut h, time + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let status = held.job.status().unwrap(); + assert_eq!(status.request.camera, camera); + assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, ev, "actual admitted job must carry EV exactly once"); + if let Some(previous) = previous_job { + assert_ne!(held.job.id(), previous, "an EV edit must not reuse the old admitted job"); + } + previous_job = Some(held.job.id()); + let frame = held.job.frame().unwrap().unwrap(); + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + // Original closed-form oracle: index-matched opaque dielectric has no + // Fresnel/specular term, so L = IEC-sRGB(128) * 0.5 / pi at normal incidence. + // Apply 2^EV once, Reinhard once, then IEC sRGB once and round to eight bits. + // No renderer BRDF/transfer helper or measured baseline supplies expectations. + let encoded = 128.0_f64 / 255.0; + let albedo = ((encoded + 0.055) / 1.055).powf(2.4); + let exposed = albedo * 0.5 / std::f64::consts::PI * 2.0_f64.powf(ev); + let mapped = exposed / (1.0 + exposed); + let srgb = if mapped <= 0.0031308 { 12.92 * mapped } else { 1.055 * mapped.powf(1.0 / 2.4) - 0.055 }; + let expected = (255.0 * srgb).round() as u8; + assert!(expected > 0 && expected < 255, "fixture must stay away from black and clipping"); + assert_eq!(png.get_pixel(7, 7).0, [expected, expected, expected, 255], "EV={ev}: actual native CPU PNG must match analytic radiance"); + if step == 0 { + baseline_png = Some(frame.png().to_vec()); + } else if step == 3 { + assert_eq!(frame.png(), baseline_png.as_ref().unwrap().as_slice(), "EV reversal must return the deterministic original PNG"); + } + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.3, false, true); + assert!(painted); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, cached.png_sha256), (held.job.id(), frame.info.png_sha256.clone())); + assert_eq!((samples, complete), (16, true)); + let uploaded = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + assert_eq!(pixels.size, [16, 16]); + assert_eq!( + pixels.pixels[7 * 16 + 7], + Color32::from_rgb(expected, expected, expected), + "the accepted texture must contain the analytic pixel" + ); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["stale"], false); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + interactive_assert_final_export_isolation(&mut h, &held.job); + assert_eq!(h.app.render_workspace.view.raytrace, final_options); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), final_size); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + } + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery") { + return; + } + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let original = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let original_visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let path = h.dir.join("interactive-accepted-to-pending-original.hdr"); + let bytes = original_hdr_bytes(192, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: path.to_string_lossy().into_owned() }; + // Even a real valid file is not admitted until inspected. An already + // displayed CPU frame must disappear, not masquerade as the new HDR intent. + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, true, true); + assert!(!painted); + output.textures_delta.clear(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.5); + assert_eq!(error, h.app.tr("render.hdr_inspect_required")); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > original_visual); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); + // A correcting inspection must respect explicit user pause. Resume then + // captures the actual checked HDR through Snapshot/CPU, rather than falling + // back to the old frame or manufacturing a successful callback. + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let checked = interactive_request(&h.app).unwrap(); + { + use sha2::{Digest, Sha256}; + assert_eq!(checked["environment"]["expected_sha256"], format!("{:x}", Sha256::digest(&bytes))); + } + interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); + interactive_clear_acceptance_frame(&mut h, epoch + 1.5, true); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(interactive::test_cache(&h.app).is_none(), "the earlier accepted image cannot return after correcting HDR"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let recovered = interactive_recovery_require_success(&mut h, epoch + 1.701, epoch + 1.8); + assert_ne!(recovered, original); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), recovered); + let frame = job.frame().unwrap().unwrap(); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + assert_eq!((cached.job, samples, complete), (recovered, 16, true)); + assert_eq!(interactive_request(&h.app).unwrap(), checked); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 2.0, true, true); + assert!(painted, "Pause retains the newly recovered actual frame"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + let (paused, paused_samples, paused_complete, paused_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (paused.job, paused.png_sha256, paused_samples, paused_complete, paused_texture), + (recovered, frame.info.png_sha256.clone(), 16, true, texture) + ); + assert!(!output.textures_delta.set.contains_key(&texture), "Pause reuses the recovered texture"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert_eq!(job.frame().unwrap().unwrap().png(), frame.png()); + interactive_assert_final_export_isolation(&mut h, &job); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +fn partial_png_contract_encode(width: u32, height: u32, pixels: Vec) -> Vec { + // Original unit input for the real decoder/receiver, not a CPU render receipt. + let pixels = image::RgbaImage::from_raw(width, height, pixels).unwrap(); + let mut png = std::io::Cursor::new(Vec::new()); + pixels.write_to(&mut png, image::ImageFormat::Png).unwrap(); + png.into_inner() +} + +fn partial_png_contract_request() -> solidcraft_engine::render::job::ImageRequest { + use solidcraft_engine::render::job::{CpuProgressiveOptions, ImageRequest, RaytraceOptions}; + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + camera: Default::default(), + width: 2, + height: 2, + background: [32, 64, 96], + transparent_background: false, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { progressive: Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 291 }), ..Default::default() }), + } +} + +fn partial_png_contract_info(png: &[u8]) -> solidcraft_engine::render::job::PartialPreviewInfo { + use sha2::{Digest, Sha256}; + use solidcraft_engine::render::{ + ExecutorId, + job::{AlphaConvention, ColourEncoding, FrameInfo, JobId, PartialPreviewInfo, PartialPreviewProjection}, + }; + // Synthetic descriptor for pure contract tests. No Host/JobHandle, capture, + // native executor or final registry is installed or claimed by this helper. + PartialPreviewInfo { + frame: FrameInfo { + job: JobId { session: 100, serial: 1, generation: 1 }, + scene_generation: 7, + backend: solidcraft_engine::render::builtin_backend().id, + executor: ExecutorId::new("cpu-raytrace").unwrap(), + width: 2, + height: 2, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, + png_sha256: format!("{:x}", Sha256::digest(png)), + }, + sequence: 1, + source_width: 2, + source_height: 2, + completed_passes: 0, + updated_prefix: 3, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + } +} + +#[test] +fn partial_png_contract_four_pixels_separate_hit_miss_black_and_unknown() { + let request = partial_png_contract_request(); + // Independently derived IEC/Reinhard bytes for linear(.25,.5,1) at EV0: + // encode(1/5), encode(1/3), encode(1/2) = (124,156,188). + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 0], sampling, 8192).unwrap(); + assert_eq!(decoded.pixels, vec![Color32::from_rgb(124, 156, 188), Color32::from_rgb(32, 64, 96), Color32::BLACK, Color32::TRANSPARENT,]); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 3); + assert!(sampling.source_unknown(), "global Unknown drives the added geometry gate"); + assert!(interactive::validate_partial_pixel(0, 0, Color32::BLACK, request.background).is_err()); + assert!(interactive::validate_partial_pixel(0, 1, Color32::TRANSPARENT, request.background).is_err()); + assert!(interactive::validate_partial_pixel(1, 0, Color32::BLACK, request.background).is_err()); + assert!(interactive::validate_partial_pixel(1, 1, Color32::BLACK, request.background).is_ok()); +} + +#[test] +fn partial_png_contract_second_prefix_keeps_nonuniform_counts_and_resolved_coverage() { + let request = partial_png_contract_request(); + // Original second-prefix source means are(.5,.25,1) and(0,1,0). + // The second has C/N=.5, so covered green2 is mapped BEFORE coverage: + // linear(.5*decode8(32), 1/3+.5*decode8(64), .5*decode8(96)), + // encoded once = (20,162,68). These PNG inputs must never be regraded by UI. + let png = partial_png_contract_encode(2, 2, vec![156, 124, 188, 255, 20, 162, 68, 255, 0, 0, 0, 255, 32, 64, 96, 255]); + let mut info = partial_png_contract_info(&png); + info.sequence = 2; + info.completed_passes = 1; + info.updated_prefix = 2; + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[2, 1, 1, 0], sampling, 8192).unwrap(); + assert_eq!( + decoded.pixels, + vec![Color32::from_rgb(156, 124, 188), Color32::from_rgb(20, 162, 68), Color32::BLACK, Color32::from_rgb(32, 64, 96),] + ); + let counts: Vec<_> = (0..4).map(|index| interactive::partial_sample_count(1, 2, index, 4, 16).unwrap()).collect(); + assert_eq!(counts, vec![2, 2, 1, 1]); + assert_eq!(sampling.sample_range(), (1, 2), "this is not uniform2SPP"); + assert_eq!(sampling.sampled_source_pixels(), 4); + assert!(!sampling.source_unknown(), "only the additional Unknown block ends; all M3 gates still apply"); +} + +#[test] +fn partial_png_contract_frontier_bounds_keep_full_pass_sentinel_and_never_wrap() { + for index in 0..4 { + assert_eq!(interactive::partial_sample_count(0, 0, index, 4, 16).unwrap(), 0); + assert_eq!(interactive::partial_sample_count(1, 0, index, 4, 16).unwrap(), 1); + assert_eq!(interactive::partial_sample_count(16, 0, index, 4, 16).unwrap(), 16); + } + for (s, k, i, p, target) in [ + (0, 4, 0, 4, 16), + (0, 0, 4, 4, 16), + (0, 0, u64::MAX, 4, 16), + (0, 0, 0, 0, 16), + (0, 0, 0, 4, 0), + (17, 0, 0, 4, 16), + (16, 1, 0, 4, 16), + (u32::MAX, 1, 0, 4, u32::MAX), + ] { + assert!(interactive::partial_sample_count(s, k, i, p, target).is_err()); + } +} + +#[test] +fn partial_png_contract_rejects_high_invalid_identity_without_burning_accepted_sequence() { + let request = partial_png_contract_request(); + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let accepted = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + assert!(interactive::validate_partial_metadata(&expected, &info, png.len(), 4, Some(accepted)).unwrap().is_none()); + let mut invalid = info.clone(); + invalid.sequence = 99; + invalid.frame.job.generation += 1; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; + invalid.frame.width = 1; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; + invalid.updated_prefix = 2; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; // advancing sequence with unchanged frontier is not new work + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + let mut next = info.clone(); + next.sequence = 2; // legitimate lower-than-rejected99 publication + next.completed_passes = 1; + next.updated_prefix = 2; + assert!(interactive::validate_partial_metadata(&expected, &next, png.len(), 4, Some(accepted)).unwrap().is_some()); + next.sequence = 0; + assert!(interactive::validate_partial_metadata(&expected, &next, png.len(), 4, Some(accepted)).is_err()); +} + +#[test] +fn partial_png_contract_decoder_refuses_unknown_blur_coverage_and_malformed_png() { + let request = partial_png_contract_request(); + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 0], sampling, 1).is_err(), "no implicit Triangle resize of Unknown"); + assert!(interactive::decode_partial_image(&request, &info, b"not a PNG", &[1, 0, 1, 0], sampling, 8192).is_err()); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 1], sampling, 8192).is_err(), "Unknown has no covered sample"); + assert!(interactive::decode_partial_image(&request, &info, &png, &[2, 0, 1, 0], sampling, 8192).is_err()); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1], sampling, 8192).is_err()); + let bad_alpha = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 128, 0, 0, 0, 255, 0, 0, 0, 0]); + let bad_info = partial_png_contract_info(&bad_alpha); + let bad_sampling = interactive::validate_partial_metadata(&expected, &bad_info, bad_alpha.len(), 4, None).unwrap().unwrap(); + assert!( + interactive::decode_partial_image(&request, &bad_info, &bad_alpha, &[1, 0, 1, 0], bad_sampling, 8192).is_err(), + "metadata admitted; sampled physical coverage must already be opaque" + ); +} + +#[test] +fn partial_png_contract_shared_plan_keeps_unrepresented_unknown_globally_blocked() { + use sha2::{Digest, Sha256}; + let mut request = partial_png_contract_request(); + request.width = 2048; + request.height = 1; + let png = partial_png_contract_encode(1024, 1, [0, 0, 0, 255].repeat(1024)); + let mut info = partial_png_contract_info(&png); + info.source_width = 2048; + info.source_height = 1; + info.frame.width = 1024; + info.frame.height = 1; + info.frame.png_bytes = png.len() as u64; + info.frame.png_sha256 = format!("{:x}", Sha256::digest(&png)); + info.updated_prefix = 2047; + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2048, 1] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 1024, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[1; 1024], sampling, 8192).unwrap(); + assert!(decoded.pixels.iter().all(|pixel| *pixel == Color32::BLACK)); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 2047); + assert!(sampling.source_unknown(), "all1024 representatives known does not observe source pixel2047"); + let plan = solidcraft_engine::render::job::PartialPreviewPlan::new(2048, 1).unwrap(); + assert_eq!(plan.source_index(0).unwrap(), 0); + assert_eq!(plan.source_index(1023).unwrap(), 2046); + assert!(plan.source_index(1024).is_err()); +} + +#[test] +fn partial_png_contract_egui_clock_throttles_attempts_without_wall_time_or_fake_frames() { + use solidcraft_engine::render::job::JobId; + use std::time::Duration; + let job = JobId { session: 100, serial: 1, generation: 1 }; + assert!(interactive::partial_request_due(None, job, Duration::ZERO)); + let first = Some((job, Duration::ZERO)); // caller records every attempt, including false + assert!(!interactive::partial_request_due(first, job, Duration::from_millis(249))); + assert!(interactive::partial_request_due(first, job, Duration::from_millis(250))); + let second = Some((job, Duration::from_millis(250))); + assert!(!interactive::partial_request_due(second, job, Duration::from_millis(499))); + assert!(interactive::partial_request_due(second, job, Duration::from_millis(500))); + let mut newer = job; + newer.serial += 1; + assert!(interactive::partial_request_due(second, newer, Duration::from_millis(251))); + let clock = interactive::monotonic(Duration::from_millis(500), 0.499); + assert_eq!(clock, Duration::from_millis(500)); + assert!(!interactive::partial_request_due(Some((job, clock)), job, Duration::from_millis(499))); +} + +#[test] +fn partial_frame_visibility_paused_unknown_yields_to_final_priority() { + use interactive::FrameVisibility; + // Policy inputs only: no Host/JobHandle, fake CPU output or native receipt. + let paused = FrameVisibility { + has_context: true, + final_active: false, + has_error: false, + paused: true, + stale: true, + revision_matches: false, + texture_ok: true, + }; + assert!(paused.paintable(), "normal M3 paused/stale image remains visible"); + assert!(paused.blocks_unknown(true), "source Unknown still blocks geometry while paused"); + assert!(!paused.blocks_unknown(false), "known source does not gain an extra gate"); + let preempted = FrameVisibility { final_active: true, ..paused }; + assert!(!preempted.paintable()); + assert!(!preempted.blocks_unknown(true), "an image hidden by a manual final cannot reserve the Model canvas"); + // This is the nonwaiting case: both production paint and the Unknown arm + // decline it, so the existing parent can reach its visible Raster fallback. +} + +#[test] +fn partial_frame_visibility_error_or_missing_texture_cannot_claim_unknown_canvas() { + use interactive::FrameVisibility; + let paused = FrameVisibility { + has_context: true, + final_active: false, + has_error: false, + paused: true, + stale: true, + revision_matches: false, + texture_ok: true, + }; + for hidden in [ + FrameVisibility { has_error: true, ..paused }, + FrameVisibility { texture_ok: false, ..paused }, + FrameVisibility { has_context: false, ..paused }, + FrameVisibility { paused: false, ..paused }, + ] { + assert!(!hidden.paintable()); + assert!(!hidden.blocks_unknown(true), "hidden pixels cannot suppress visible Raster or its geometry targets"); + } + let current = FrameVisibility { paused: false, stale: false, revision_matches: true, ..paused }; + assert!(current.paintable()); + assert!(current.blocks_unknown(true), "all-known representatives cannot erase global source Unknown"); + assert!(!FrameVisibility { stale: true, ..current }.blocks_unknown(true)); + assert!(!FrameVisibility { revision_matches: false, ..current }.blocks_unknown(true)); + // Existing waiting/input-cleanup regressions stay in the untouched222 prefix. + // The production awaiting_current_frame arm is not gated by this predicate. +} + +mod cpu_optical_material_routing { + use super::*; + + fn bind_recipe(h: &mut Harness, name: &str, recipe: &str, boundary: materials::Boundary) { + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == name).unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe(recipe).unwrap(); + // These represent explicit author actions, not a converter's guesses. + binding.glass.boundary = boundary; + binding.cpu_optics = true; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + } + + fn fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":4,"center":[0,0,2],"body_name":"Optics"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.lights = Some(vec![]); + h.app.render_workspace.view.raytrace.shadows = false; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [1.0; 3]; + h.app.render_workspace.view.cpu.intensity = 1.0; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.background = [255; 3]; + h.app.cam = Camera { distance: 50.0, fov: 0.0, ..Default::default() }; + h.app.cam.set_view(StandardView::Top); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + h.app.session.mark_saved(); + h + } + + fn wire(h: &Harness) -> Value { + runtime_image_request(&h.app, false).unwrap() + } + + fn directional_shadow_fixture(choices: &[bool]) -> Harness { + use solidcraft_engine::render::job::DirectionalLightOptions; + assert!(!choices.is_empty() && choices.len() <= 2); + let mut h = Harness::new(); + for index in 0..choices.len() { + h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"center":[index as f64 * 4.0,0,2],"body_name":format!("Shadow{index}")})).unwrap(); + } + h.app.run("render.scene", json!({})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.shadows = true; + h.app.render_workspace.view.raytrace.lights = + Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 2.0 }]); + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.materials.enabled = true; + let targets = materials::read_targets(&mut h.app).unwrap(); + for (index, shadows) in choices.iter().copied().enumerate() { + let target = targets.iter().find(|target| target.name == format!("Shadow{index}")).unwrap().clone(); + let mut binding = materials::Binding::new(target, &h.app); + binding.cpu_optics = true; + binding.glass_enabled = true; + binding.glass.boundary = materials::Boundary::Box; + binding.glass.shadows = shadows; + h.app.render_workspace.view.materials.bindings.push(binding); + } + h.app.session.mark_saved(); + h + } + + fn directional_shadow_refusal_is_atomic(h: &Harness, key: Option<&str>) { + let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"preserve"}); + cpu::params(&h.app, &mut request).unwrap(); + let before = request.clone(); + let authored = format!("{:?}", h.app.render_workspace.view.materials); + let options = json!(h.app.render_workspace.view.raytrace); + let error = materials::params(&h.app, &mut request).unwrap_err(); + if let Some(key) = key { + assert!(error.contains(h.app.tr(key)), "{key}: {error}"); + } + assert_eq!(request, before); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); + assert_eq!(json!(h.app.render_workspace.view.raytrace), options); + } + + #[test] + fn cpu_directional_shadow_uniform_assignments_lower_typed_wire_without_changing_authored_options() { + use solidcraft_engine::render::job::{CpuDielectricTransport, CpuProgressiveOptions, RaytraceOptions}; + for shadows in [false, true] { + for progressive in [false, true] { + for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { + let mut h = directional_shadow_fixture(&[shadows, shadows]); + h.app.render_workspace.view.raytrace.dielectric_transport = policy; + h.app.render_workspace.view.raytrace.progressive = progressive.then_some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 411 }); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let authored = format!("{:?}", h.app.render_workspace.view.materials); + let mut expected = json!({"settings":{"exposure_ev":1.25}}); + cpu::params(&h.app, &mut expected).unwrap(); + let request = runtime_image_request(&h.app, false).unwrap(); + let mut options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + options.validate().unwrap(); + assert_eq!(options.directional_shadow_transmission, shadows); + assert!(options.shadows); + assert_eq!(options.dielectrics.len(), 2); + assert_eq!(options.dielectric_transport, policy); + assert_eq!(options.progressive, h.app.render_workspace.view.raytrace.progressive); + assert!(options.dielectrics.iter().all(|body| body.ior == 1.5 && body.absorption_per_mm == [0.0; 3])); + assert!(request["raytrace"]["dielectrics"].as_array().unwrap().iter().all(|body| body.get("shadow_transmission").is_none())); + if !shadows { + assert!(request["raytrace"].get("directional_shadow_transmission").is_none()); + } + options.dielectrics.clear(); + options.directional_shadow_transmission = false; + assert_eq!(json!(options), expected["raytrace"], "no other CPU option may change"); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + } + } + } + } + + #[test] + fn cpu_directional_shadow_mixed_body_choices_refuse_both_orders_without_erasing_off() { + for choices in [[false, true], [true, false]] { + let h = directional_shadow_fixture(&choices); + directional_shadow_refusal_is_atomic(&h, Some("render.cpu_shadow_mixed")); + } + } + + #[test] + fn cpu_directional_shadow_all_on_keeps_global_shadows_environment_nesting_and_light_refusals() { + for case in ["global_off", "constant", "hdr", "nested", "reflections", "punctual", "area"] { + let mut h = directional_shadow_fixture(&[true, true]); + match case { + "global_off" => h.app.render_workspace.view.raytrace.shadows = false, + "constant" => h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant, + "hdr" => { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-shadow-adapter.hdr"); + } + "nested" => h.app.render_workspace.view.cpu.nested_media = true, + "reflections" => h.app.render_workspace.view.raytrace.reflections = Some(Default::default()), + "punctual" => { + h.app.render_workspace.view.raytrace.punctual_lights = Some(serde_json::from_value(json!([{ + "position_mm":[0,0,100],"color":[1,1,1],"intensity":2,"reference_distance_mm":100,"minimum_distance_mm":0.01 + }])).unwrap()); + } + "area" => { + h.app.render_workspace.view.raytrace.area_lights = Some(serde_json::from_value(json!([{ + "center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3 + }])).unwrap()); + } + _ => unreachable!(), + } + h.app.render_workspace.view.raytrace.validate().unwrap(); + directional_shadow_refusal_is_atomic(&h, None); + } + } + + #[test] + fn cpu_directional_shadow_all_on_preserves_identity_permission_duplicate_and_boundary_gates() { + for case in ["stale", "duplicate", "closed", "permission"] { + let mut h = directional_shadow_fixture(&[true, true]); + match case { + "stale" => { + h.app.run("appearance.assign", json!({"bodies":["Shadow0"],"color":"#123456"})).unwrap(); + } + "duplicate" => { + let duplicate = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings.push(duplicate); + } + "closed" => h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Closed, + "permission" => h.app.render_workspace.view.materials.bindings[0].cpu_optics = false, + _ => unreachable!(), + } + directional_shadow_refusal_is_atomic(&h, None); + } + } + + #[test] + fn cpu_directional_shadow_inactive_off_body_is_not_selected_for_transmission() { + use solidcraft_engine::render::job::RaytraceOptions; + let mut h = directional_shadow_fixture(&[true, false]); + h.app.render_workspace.view.materials.bindings[1].enabled = false; + let request = runtime_image_request(&h.app, false).unwrap(); + let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert!(options.directional_shadow_transmission); + assert_eq!(options.dielectrics.len(), 1); + assert_eq!(options.dielectrics[0].body_name, "Shadow0"); + assert!(!h.app.render_workspace.view.materials.bindings[1].glass.shadows); + assert!(!h.app.render_workspace.view.materials.bindings[1].enabled); + } + + #[test] + fn cpu_directional_shadow_default_false_and_conflicting_global_intent_are_preserved() { + use solidcraft_engine::render::job::RaytraceOptions; + assert!(!RaytraceOptions::default().directional_shadow_transmission); + assert!(json!(RaytraceOptions::default()).get("directional_shadow_transmission").is_none()); + let h = directional_shadow_fixture(&[false, false]); + let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"retain"}); + cpu::params(&h.app, &mut request).unwrap(); + request["raytrace"]["directional_shadow_transmission"] = json!(true); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_shadow_conflict"))); + assert_eq!(request, before); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); + let mut h = directional_shadow_fixture(&[true, false]); + h.app.render_workspace.view.materials.enabled = false; + let before = request.clone(); + materials::params(&h.app, &mut request).unwrap(); + assert_eq!(request, before, "disabled materials do not rewrite an unrelated request"); + } + + #[test] + fn cpu_directional_shadow_adapter_messages_are_delivered_in_nine_languages() { + for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + let locale = crate::i18n::Locale::for_language(language); + for key in ["render.cpu_directional_shadow_help", "render.cpu_shadow_conflict", "render.cpu_shadow_mixed"] { + assert_ne!(locale.text(key), key, "{language}: {key}"); + assert!(!locale.text(key).is_empty(), "{language}: {key}"); + } + } + } + + #[test] + fn explicit_cpu_recipe_builds_typed_optics_with_independent_linear_units_and_no_design_edit() { + use solidcraft_engine::render::{ + job::{DielectricBoundary, RaytraceOptions}, + transmission::Transmission, + }; + let h = fixture(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let request = wire(&h); + let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert_eq!(options.dielectrics.len(), 1); + let material = &options.dielectrics[0]; + assert_eq!((material.body_index, material.body_name.as_str()), (0, "Optics")); + assert_eq!(material.boundary, DielectricBoundary::ClosedBox); + assert_eq!(material.ior, 1.5); + assert_eq!(material.thickness_mm, 0.0); + let [r, g, b] = material.absorption_per_mm; + assert!((r - 0.005050676829379866).abs() < 1e-15); + assert!((g - 0.0025125839633753626).abs() < 1e-15); + assert_eq!(b, 0.0); + // This tests coefficient lowering only. Native pixel tests below test transport. + let medium = Transmission::new(solidcraft_engine::geom::Vec3::new(r, g, b), None).unwrap(); + for (distance, expected) in [(4.0, [0.98, 0.99, 1.0]), (8.0, [0.9604, 0.9801, 1.0])] { + let t = medium.attenuation(distance).unwrap(); + for (actual, expected) in [t.x, t.y, t.z].into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-12); + } + } + assert!(request["raytrace"].get("clear_coats").is_none()); + assert!(request["raytrace"].get("textures").is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + assert!(setups::snapshot(&h.app).is_err(), "transient CPU optics are not portable GPU saved optics"); + } + + #[test] + fn legacy_gpu_binding_and_closed_recipe_still_need_explicit_cpu_route_and_box_choice() { + let mut h = fixture(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.cpu_optics = false; + binding.glass = materials::Glass::recipe("starter.glass.low-iron-clear").unwrap(); + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_explicit"))); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_boundary"))); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let mut gpu = json!({}); + materials::params(&h.app, &mut gpu).unwrap(); + assert_eq!(gpu["raytrace"]["dielectrics"][0]["boundary"], "closed_mesh"); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(materials::params(&h.app, &mut json!({})).is_err()); + } + + #[test] + fn thin_recipe_preserves_authored_shadow_intent_until_explicit_edit() { + let mut h = fixture(); + h.app.render_workspace.view.materials.bindings[0].glass = materials::Glass::recipe("starter.glass.thin-clear").unwrap(); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_unsupported"))); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + // User deliberately disables the distinct GPU transmitted-shadow approximation. + h.app.render_workspace.view.materials.bindings[0].glass.shadows = false; + let request = wire(&h); + assert_eq!(request["raytrace"]["dielectrics"][0]["boundary"], "thin_sheet"); + assert_eq!(request["raytrace"]["dielectrics"][0]["thickness_mm"], 2.0); + assert!(request["raytrace"]["dielectrics"][0].get("shadow_transmission").is_none()); + // The box fixture is NOT a certified thin surface; native admission must refuse below. + } + + #[test] + fn unsupported_optical_intent_refuses_atomically_instead_of_erasing_flags_or_maps() { + for case in ["coat", "maps", "shadows", "subsurface", "no_glass"] { + let mut h = fixture(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + match case { + "coat" => binding.coat_enabled = true, + "maps" => { + binding.maps_enabled = true; + binding.maps.normal = "authored-normal.png".into(); + } + "shadows" => binding.glass.shadows = true, + "subsurface" => { + binding.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }) + } + _ => { + binding.glass_enabled = false; + binding.coat_enabled = true; + } + } + let intent = format!("{:?}", h.app.render_workspace.view.materials); + let mut request = json!({"settings":{"exposure_ev":0},"sentinel":"retain"}); + cpu::params(&h.app, &mut request).unwrap(); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).is_err(), "{case}"); + assert_eq!(request, before, "failed lowering must not partially replace CPU options: {case}"); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), intent, "{case}"); + } + } + + #[test] + fn cpu_optical_request_preserves_hdr_and_all_preexisting_cpu_numeric_options() { + use solidcraft_engine::render::job::RaytraceOptions; + let mut h = fixture(); + h.app.render_workspace.view.raytrace = serde_json::from_value(json!({ + "budget":"studio","primary_samples":4,"shadows":true, + "lights":[{"direction":[0,0,1],"color":[1,0.5,0.25],"intensity":2}], + "punctual_lights":[{"position_mm":[0,0,100],"color":[0.25,0.5,1],"intensity":4, + "reference_distance_mm":100,"minimum_distance_mm":0.01,"cone":{"emitted_axis":[0,0,-1],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.2}}], + "area_lights":[{"center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3}], + "area_samples":16,"seed":42 + })).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-optical-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = 0.75; + h.app.render_workspace.view.cpu.intensity = 2.0; + h.app.render_workspace.view.cpu.samples = 64; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + let base = json!(h.app.render_workspace.view.raytrace); + let mut request = json!({"settings":{"exposure_ev":1.25}}); + cpu::params(&h.app, &mut request).unwrap(); + let cpu_request = request.clone(); + materials::params(&h.app, &mut request).unwrap(); + let mut decoded: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert_eq!(decoded.dielectrics.len(), 1); + decoded.dielectrics.clear(); + assert_eq!(json!(decoded), cpu_request["raytrace"], "only typed dielectrics may change"); + assert_eq!(request["environment"], cpu_request["environment"]); + assert_eq!(request["environment"]["path"], "not-read-by-optical-ui.hdr"); + assert_eq!(request["settings"]["exposure_ev"], 0.0); + assert_eq!(request["raytrace"]["exposure_ev"], 1.25); + assert_eq!(json!(h.app.render_workspace.view.raytrace), base); + } + + #[test] + fn optical_binding_refuses_hidden_changed_ordinal_wrong_feature_and_wrong_document() { + let mut h = fixture(); + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + assert!(runtime_image_request(&h.app, false).is_err(), "visibility need not change revision"); + h.app.session.visibility.hidden_bodies.clear(); + assert!(runtime_image_request(&h.app, false).is_ok()); + h.app.render_workspace.view.materials.bindings[0].target.ordinal = 1; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.render_workspace.view.materials.bindings[0].target.stable_target.as_mut().unwrap().feature += 1; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.render_workspace.view.materials.bindings[0].target.stable_target.as_mut().unwrap().occurrence_path = vec![999]; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original; + let document = h.app.session.doc.clone(); + h.app.session.doc = Arc::new((*document).clone()); + assert!(runtime_image_request(&h.app, false).is_err(), "same numerical revision is not same document"); + } + + #[test] + fn optical_revalidation_is_explicit_and_same_body_only() { + let mut h = fixture(); + let mut original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + materials::revalidate(&mut h.app, &mut original).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + assert!(runtime_image_request(&h.app, false).is_ok()); + original.target.name = "Same name is insufficient".into(); + assert!(materials::revalidate(&mut h.app, &mut original).is_err()); + assert_eq!(original.target.name, "Same name is insufficient"); + } + + #[test] + fn optical_limits_duplicates_and_hostile_coefficients_keep_original_request_intact() { + let mut h = fixture(); + for bad in [f64::NAN, f64::INFINITY, -1.0, 3.01] { + h.app.render_workspace.view.materials.bindings[0].glass.ior = bad; + assert!(runtime_image_request(&h.app, false).is_err()); + } + h.app.render_workspace.view.materials.bindings[0].glass.ior = 1.5; + for bad in [f64::NAN, f64::INFINITY, -0.1, 100.01] { + h.app.render_workspace.view.materials.bindings[0].glass.absorption[0] = bad; + assert!(runtime_image_request(&h.app, false).is_err()); + } + h.app.render_workspace.view.materials.bindings[0].glass.absorption = [0.0; 3]; + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings.push(original.clone()); + assert!(runtime_image_request(&h.app, false).is_err(), "duplicate target is not two media"); + h.app.render_workspace.view.materials.bindings = vec![original; 9]; + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_limit"))); + } + + #[test] + fn progressive_optics_preserves_identity_and_saved_gpu_conflicts_without_mutation() { + let mut h = fixture(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let authored = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + let progressive_final = runtime_image_request(&h.app, false).unwrap(); + let final_options: RaytraceOptions = serde_json::from_value(progressive_final["raytrace"].clone()).unwrap(); + final_options.validate().unwrap(); + assert_eq!(final_options.primary_samples, 1); + assert_eq!(final_options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(final_options.progressive.unwrap().seed, 0); + let optics = progressive_final["raytrace"]["dielectrics"].clone(); + assert_eq!(optics.as_array().unwrap().len(), 1); + assert_eq!(optics[0]["body_name"], "Optics"); + assert_eq!(optics[0]["boundary"], "closed_box"); + assert_eq!(optics[0]["ior"], 1.5); + assert!(h.app.render_workspace.view.materials.bindings[0].cpu_optics); + let from_progressive = interactive_request(&h.app).unwrap(); + assert_eq!(from_progressive["raytrace"]["dielectrics"], optics, "preview conversion cannot erase or replace the authored optical material"); + assert!(h.app.render_workspace.view.materials.bindings[0].glass_enabled); + h.app.render_workspace.view.raytrace.progressive = None; + let from_fixed = interactive_request(&h.app).unwrap(); + assert_eq!(from_fixed["raytrace"]["dielectrics"], optics, "Fixed editor preview still carries certified optics"); + let progressive_input: RaytraceOptions = serde_json::from_value(from_progressive["raytrace"].clone()).unwrap(); + progressive_input.validate().unwrap(); + assert_eq!(progressive_input.primary_samples, 1); + assert_eq!(progressive_input.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(progressive_input.progressive.unwrap().seed, 0); + let fixed_input: RaytraceOptions = serde_json::from_value(from_fixed["raytrace"].clone()).unwrap(); + fixed_input.validate().unwrap(); + assert_eq!(fixed_input.primary_samples, 1); + assert!(fixed_input.progressive.is_none(), "the UI Fixed DTO stays Fixed until the engine preview conversion"); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none(), "constructing preview intent cannot change the manual-final editor"); + #[cfg(not(target_arch = "wasm32"))] + if native_host(&mut h, "progressive_bridge_obsolete_guard_adaptation") { + use solidcraft_engine::render::job::{JobId, Phase, interactive::VisualRevision}; + use std::time::Duration; + // Same original20x20/one-pixel/50-distance inputs: this is actual + // capture/admission/completion, not a Beer pixel oracle (jitter may miss). + let mut final_params = progressive_final.clone(); + final_params["progressive_feedback"] = json!(true); + let checked = h.app.run("render.preflight", final_params.clone()).unwrap(); + let started = h.app.run("render.start", final_params).unwrap(); + let final_id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let final_job = h.app.session.render_job_handle(final_id).unwrap(); + let final_status = final_job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(final_status.progress.phase, Phase::Completed, "{:?}", final_status.error); + assert_eq!(serde_json::to_value(&final_status.request).unwrap(), checked["request"]); + assert_eq!(json!(final_status.request.raytrace), progressive_final["raytrace"]); + assert!(!final_status.options.nested_media); + assert!(final_job.protected_preview_report().unwrap().is_some()); + let final_bytes = final_job.frame().unwrap().unwrap().png().to_vec(); + for (index, params) in [&from_progressive, &from_fixed].into_iter().enumerate() { + let context = h.app.session.interactive_render().unwrap(); + context + .enable(VisualRevision { scene_generation: h.app.session.revision, visual_revision: index as u64 + 1 }, Duration::ZERO) + .unwrap(); + let ticket = context.capture(Duration::from_millis(200)).unwrap().unwrap(); + let snapshot = context.snapshot(&h.app.session, ticket, params).unwrap(); + assert!(snapshot.run().unwrap(), "real optical snapshot must be admitted/adopted"); + let job = context.current().unwrap().unwrap(); + let status = job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + let options = status.request.raytrace.as_ref().unwrap(); + assert_eq!(serde_json::to_value(&options.dielectrics).unwrap(), optics); + assert_eq!(options.primary_samples, 1); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(options.progressive.unwrap().seed, 0); + assert_eq!((status.request.width, status.request.height), (1, 1)); + assert!(!status.options.nested_media); + assert_eq!(job.id(), ticket.job_id()); + assert!(job.frame().unwrap().is_some()); + assert!(h.app.session.render_job_handle(job.id()).is_err(), "Interactive keeps a separate non-export owner"); + context.disable().unwrap(); + assert_eq!(h.app.session.render_job_handle(final_id).unwrap().frame().unwrap().unwrap().png(), final_bytes.as_slice()); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), authored); + let mut request = wire(&h); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_optics_conflict"))); + assert_eq!(request, before); + let target = h.app.render_workspace.view.materials.bindings[0].target.stable_target.clone().unwrap(); + h.app + .render_workspace + .view + .draft + .optics + .set( + solidcraft_engine::doc::render_optics::SavedOptics { + target, + optics: solidcraft_engine::doc::render_optics::OpticalMaterial { + ior: 1.5, + absorption_per_mm: [0.0; 3], + boundary: solidcraft_engine::doc::render_optics::OpticalBoundary::ClosedMesh, + thickness_mm: 0.0, + shadow_transmission: false, + subsurface: None, + }, + }, + false, + ) + .unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + assert_eq!(h.app.render_workspace.view.draft.optics.len(), 1); + } + + #[test] + fn nested_cpu_route_is_an_explicit_cpu_choice_independent_of_gpu_legacy_state() { + let mut h = fixture(); + h.app.render_workspace.view.studio.nested_media = true; + assert_eq!(wire(&h)["nested_media"], false); + h.app.render_workspace.view.cpu.nested_media = true; + assert_eq!(wire(&h)["nested_media"], true); + h.app.render_workspace.view.studio.nested_media = false; + assert_eq!(wire(&h)["nested_media"], true); + h.app.render_workspace.view.cpu.nested_media = false; + assert_eq!(wire(&h)["nested_media"], false); + } + + #[cfg(not(target_arch = "wasm32"))] + fn native_host(h: &mut Harness, case: &str) -> bool { + use solidcraft_engine::render::job::CpuHost; + let host = CpuHost::for_platform().unwrap(); + let available = host.kind() == solidcraft_engine::render::job::HostKind::NativeWorker + && host.is_available() + && host.validate_integrator(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + if !available { + let request = wire(h); + assert!(image_params(&h.app).is_err()); + assert!(h.app.run("render.preflight", request.clone()).is_err()); + assert!(h.app.run("render.start", request).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + eprintln!("CPU_OPTICS_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + return false; + } + eprintln!("CPU_OPTICS_BRANCH case={case} cpu_supported=true"); + true + } + + #[cfg(not(target_arch = "wasm32"))] + fn check_start_pixel(h: &mut Harness, expected: [u8; 4]) { + use solidcraft_engine::render::job::{JobId, Phase}; + let request = image_params(&h.app).unwrap(); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(checked["request"]["raytrace"]["dielectrics"], request["raytrace"]["dielectrics"]); + assert_eq!(image_params(&h.app).unwrap(), request, "Check and Start must capture identical optical intent"); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let started = h.app.run("render.start", request.clone()).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + assert_eq!(status.options.nested_media, request["nested_media"].as_bool().unwrap()); + let frame = handle.frame().unwrap().unwrap(); + let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(*image.get_pixel(0, 0), image::Rgba(expected)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_library_box_reaches_same_cpu_check_start_and_real_beer_pixels() { + let mut h = fixture(); + if !native_host(&mut h, "library_box") { + return; + } + // Explicit author edit isolates Beer: index-matched boundaries have zero + // Fresnel reflection, 4 mm actual distance yields [.98,.99,1]. + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + glass.ior = 1.0; + glass.recipe = None; + check_start_pixel(&mut h, [187, 187, 188, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_optics_admission_preserves_opacity_and_refuses_false_thin_certificate() { + let mut h = fixture(); + if !native_host(&mut h, "opacity_and_certificate") { + return; + } + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Thin; + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + assert!(h.app.run(command, request.clone()).is_err(), "twelve triangles are not a thin-sheet certificate"); + } + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Box; + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); + let mut binding = h.app.render_workspace.view.materials.bindings[0].clone(); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = binding; + let document = h.app.session.doc.clone(); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("opaque body and face"), "{error}"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(solidcraft_engine::product_scene::extract(&h.app.session).unwrap().meshes[0].opacity, 0.25); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_thin_library_recipe_uses_actual_imported_planar_certificate_and_virtual_distance() { + let mut h = fixture(); + if !native_host(&mut h, "library_thin") { + return; + } + let path = h.dir.join("original-optical-sheet.stl"); + // Original one-triangle geometry, not a box proxy or commercial fixture. + std::fs::write(&path, b"solid OriginalSheet\nfacet normal 0 0 1\nouter loop\nvertex -20 -20 2\nvertex 20 -20 2\nvertex 0 20 2\nendloop\nendfacet\nendsolid OriginalSheet\n").unwrap(); + h.app.run("file.insert_mesh", json!({"path":path,"name":"OriginalSheet"})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + h.app.render_workspace.view.materials.bindings.clear(); + let targets = materials::read_targets(&mut h.app).unwrap(); + assert_eq!(targets.len(), 1); + let name = targets[0].name.clone(); + bind_recipe(&mut h, &name, "starter.glass.thin-clear", materials::Boundary::Thin); + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows, "do not silently delete the recipe's shadow intent"); + glass.shadows = false; // explicit compatible user policy + glass.ior = 1.0; // explicit index-matched Beer experiment + glass.recipe = None; + assert_eq!(solidcraft_engine::product_scene::extract(&h.app.session).unwrap().meshes[0].mesh.triangles.len(), 1); + // 2 mm virtual normal distance -> [.95,.98,.99]; Reinhard+sRGB bytes. + check_start_pixel(&mut h, [185, 187, 187, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_library_nested_opt_in_preserves_real_child_medium_and_default_refusal() { + let mut h = fixture(); + if !native_host(&mut h, "library_nested") { + return; + } + h.app.run("solid.box", json!({"length":10,"width":10,"height":2,"center":[0,0,2],"operation":"new","body_name":"Inner"})).unwrap(); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + bind_recipe(&mut h, "Inner", "starter.glass.amber-tint", materials::Boundary::Box); + for binding in &mut h.app.render_workspace.view.materials.bindings { + binding.glass.ior = 1.0; // explicit index-matched experiment, not renderer conversion + binding.glass.recipe = None; + } + let request = image_params(&h.app).unwrap(); + assert_eq!(request["nested_media"], false); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("nested, touching or overlapping"), "{error}"); + } + h.app.render_workspace.view.cpu.nested_media = true; + // Geometry gives 2 mm outer + 2 mm inner, replacing rather than adding + // parent extinction inside the child. Linear RGB: + // sqrt(.98)*.84^(2/3), sqrt(.99)*.38^(2/3), .08^(2/3). + // Independent Reinhard+sRGB quantisation -> [182,158,110]. + check_start_pixel(&mut h, [182, 158, 110, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_optics_refuses_face_alpha_and_general_closed_geometry_without_repairs() { + let mut h = fixture(); + if !native_host(&mut h, "face_alpha_and_sphere") { + return; + } + h.app.run("appearance.assign", json!({"body":"Optics","faces":[[0,0,4]],"color":"#abcdef","opacity":0.5})).unwrap(); + let mut binding = h.app.render_workspace.view.materials.bindings[0].clone(); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = binding; + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + assert_eq!(scene.meshes[0].opacity, 1.0); + assert!(scene.meshes[0].faces.iter().any(|face| face.opacity == 0.5)); + let document = h.app.session.doc.clone(); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("opaque body and face"), "{error}"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + h.app.run("solid.sphere", json!({"radius":3,"center":[30,0,3],"body_name":"Sphere","operation":"new"})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Sphere", "starter.glass.low-iron-clear", materials::Boundary::Box); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + assert!(h.app.run(command, request.clone()).is_err(), "an explicitly selected Box still needs an actual box certificate"); + } + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Box); + } + + #[test] + fn cpu_optics_preserves_reflection_intent_for_existing_transport_conflict() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = fixture(); + cpu::set_reflection(&mut h.app, "Optics", Some(ReflectionMode::Mirror)).unwrap(); + let request = wire(&h); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Optics"); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Optics"); + // Retaining both preserves the engine's explicit same-target transport + // refusal; the adapter does not silently delete the reflection binding. + assert!(h.app.render_workspace.view.raytrace.reflections.is_some()); + } + + #[test] + fn cpu_optics_keeps_reflections_on_a_separate_exact_body() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = fixture(); + h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"corner":[30,0,0],"body_name":"Reflector","operation":"new"})).unwrap(); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + let before = h.app.render_workspace.view.raytrace.reflections.clone().unwrap(); + let request = wire(&h); + assert_eq!(request["raytrace"]["reflections"], json!(before)); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Optics"); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Reflector"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_original_library_ior_and_hdr_survive_check_start_and_captured_file_change() { + use sha2::{Digest, Sha256}; + use solidcraft_engine::render::job::{JobId, Phase}; + let mut h = fixture(); + if !native_host(&mut h, "library_ior_hdr") { + return; + } + let path = h.dir.join("original-optical-white.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input(path.to_str().unwrap()); + h.app.render_workspace.view.cpu.samples = 4; + let request = image_params(&h.app).unwrap(); + assert_eq!(request["raytrace"]["dielectrics"][0]["ior"], 1.5, "the original recipe's IOR reaches the real consumer"); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(checked["request"]["raytrace"], request["raytrace"]); + assert_eq!(image_params(&h.app).unwrap(), request); + let started = h.app.run("render.start", request.clone()).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + // Start has captured immutable bytes; this does not depend on whether + // its tiny job has already finished by the time the file is replaced. + std::fs::write(&path, b"changed after capture").unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + // CPU status carries exactly 32 byte values; the captured request uses + // the canonical lowercase hex HdrId wire form. Normalize independently + // of HdrId's production serializer/parser and keep absent/type failures. + let captured_sha256: [u8; 32] = serde_json::from_value(json!(status.environment).get("source_sha256").unwrap().clone()).unwrap(); + let expected_hex = request["environment"]["expected_sha256"].as_str().unwrap(); + assert_eq!(expected_hex.len(), 64); + assert!(expected_hex.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))); + let expected_sha256: [u8; 32] = std::array::from_fn(|index| u8::from_str_radix(&expected_hex[index * 2..index * 2 + 2], 16).unwrap()); + let original_sha256: [u8; 32] = Sha256::digest(&bytes).into(); + assert_eq!(captured_sha256, expected_sha256); + assert_eq!(captured_sha256, original_sha256); + let frame = handle.frame().unwrap().unwrap(); + let pixels = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (1, 1)); + assert!(pixels.get_pixel(0, 0).0[..3].iter().all(|channel| *channel > 0), "real optical output must not be black"); + assert!(h.app.run("render.preflight", request).is_err(), "a fresh capture must detect the changed HDR"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_eight_optical_library_targets_admit_without_raising_the_ninth_target_limit() { + let mut h = fixture(); + if !native_host(&mut h, "eight_library_targets") { + return; + } + for index in 1..=8 { + h.app + .run( + "solid.box", + json!({"length":2,"width":2,"height":2,"corner":[30*index,0,0],"body_name":format!("Optics{index}"),"operation":"new"}), + ) + .unwrap(); + } + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + for index in 1..8 { + bind_recipe(&mut h, &format!("Optics{index}"), "starter.glass.low-iron-clear", materials::Boundary::Box); + } + let request = image_params(&h.app).unwrap(); + assert_eq!(request["raytrace"]["dielectrics"].as_array().unwrap().len(), 8); + h.app.run("render.preflight", request).unwrap(); + bind_recipe(&mut h, "Optics8", "starter.glass.low-iron-clear", materials::Boundary::Box); + assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_optics_limit"))); + } + + #[test] + fn all_original_glass_recipes_keep_their_authored_coefficients_on_the_explicit_cpu_route() { + use solidcraft_engine::doc::appearance_pack::{Recipe, STARTER_PACK}; + let mut h = fixture(); + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let glass = materials::Glass::recipe(preset.id).unwrap(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.glass = glass; + if binding.glass.boundary == materials::Boundary::Closed { + binding.glass.boundary = materials::Boundary::Box; // explicit subset selection + } else { + assert!(binding.glass.shadows); + binding.glass.shadows = false; // explicit unsupported-policy edit + } + let request = wire(&h); + let material = &request["raytrace"]["dielectrics"][0]; + assert_eq!(material["ior"], recipe.dielectric_ior); + let sigma: [f64; 3] = serde_json::from_value(material["absorption_per_mm"].clone()).unwrap(); + for (sigma, transmission) in sigma.into_iter().zip(recipe.transmission_linear_rgb) { + assert!(((-sigma * recipe.reference_path_mm).exp() - transmission).abs() < 1e-12); + } + count += 1; + } + assert_eq!(count, 6); + assert!(materials::Glass::recipe("SELENE-AP-029").is_err(), "an opaque vial surrogate does not become physical glass"); + } + + #[test] + fn cpu_optical_route_messages_are_present_in_all_nine_delivered_languages() { + for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + let locale = crate::i18n::Locale::for_language(language); + for key in [ + "render.cpu_optics_boundary", + "render.cpu_optics_conflict", + "render.cpu_optics_enable", + "render.cpu_optics_explicit", + "render.cpu_optics_fixed", + "render.cpu_optics_help", + "render.cpu_optics_limit", + "render.cpu_optics_request", + "render.cpu_optics_saved", + "render.cpu_optics_unsupported", + ] { + assert_ne!(locale.text(key), key, "{language}: {key}"); + assert!(!locale.text(key).is_empty(), "{language}: {key}"); + } + } + } + + fn editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 2400.0))), + events, + ..Default::default() + }, + |ui| { + ui.set_width(420.0); + materials::selection_controls(&mut h.app, ui, Some("Optics")); + }, + ); + output.textures_delta.clear(); + } + + fn editor_click(h: &mut Harness, id: &str) { + let at = crate::scenario::rect_of(id).unwrap().center(); + for pressed in [true, false] { + editor_frame( + h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + editor_frame(h, vec![]); + } + + #[test] + fn clicked_cpu_optics_uses_existing_selection_editor_without_reinterpreting_gpu_binding() { + let mut h = fixture(); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = false; + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + editor_frame(&mut h, vec![]); + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + editor_click(&mut h, &heading); + assert!(runtime_image_request(&h.app, false).is_err(), "opening the editor grants no CPU intent"); + editor_click(&mut h, "render:glass-recipe-select"); + editor_click(&mut h, "render:glass:starter.glass.low-iron-clear"); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + editor_click(&mut h, "render:cpu-optics-enable"); + assert!(h.app.render_workspace.view.materials.bindings[0].cpu_optics); + assert!(runtime_image_request(&h.app, false).is_err(), "Closed recipe cannot turn itself into a Box"); + editor_click(&mut h, "render:optics-boundary-box"); + assert_eq!(wire(&h)["raytrace"]["dielectrics"][0]["boundary"], "closed_box"); + editor_click(&mut h, "render:cpu-optics-nested"); + assert_eq!(wire(&h)["nested_media"], true); + editor_click(&mut h, "render:cpu-optics-enable"); + assert!(runtime_image_request(&h.app, false).is_err()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[test] + fn clicked_cpu_boundary_does_not_silently_clear_transmitted_shadow_or_subsurface_intent() { + let mut h = fixture(); + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + glass.shadows = true; + glass.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + editor_frame(&mut h, vec![]); + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + editor_click(&mut h, &heading); + editor_click(&mut h, "render:optics-boundary-thin"); + let glass = &h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows); + assert!(glass.subsurface.is_some(), "selecting a different CPU boundary is not consent to remove scattering"); + assert!(runtime_image_request(&h.app, false).is_err()); + editor_click(&mut h, "render:optics-boundary-box"); + let glass = &h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows, "the GPU boundary default must not erase unsupported CPU shadow intent"); + assert!(glass.subsurface.is_some()); + assert!(runtime_image_request(&h.app, false).is_err()); + } +} + +// Additive scope imports for the sealed optical fixtures; UI247 stays byte-identical. +use serde_json::Value; +use solidcraft_engine::render::StandardView; + +#[cfg(not(target_arch = "wasm32"))] +mod manual_final_cpu_feedback_tests { + use super::*; + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions, HostKind, JobHandle, PartialPreviewPlan, PartialPreviewProjection, Phase}; + + fn fixture(width: u32, height: u32, samples: u32, background: [u8; 3], case: &str) -> Option { + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + let available = host.kind() == HostKind::NativeWorker && host.is_available() && host.validate_integrator(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.ui.tab = "RENDER".into(); + let view = &mut h.app.render_workspace.view; + view.method = ImageMethod::CpuRaytrace; + view.draft.width = width; + view.draft.height = height; + view.draft.background = background; + view.draft.stage = Default::default(); + view.draft.surfaces = Default::default(); + assert!(view.draft.stage.is_empty()); + assert!(view.draft.surfaces.is_empty()); + view.draft.exposure_ev = 0.0; + view.transparent = false; + view.raytrace = RaytraceOptions { + primary_samples: 1, + lights: Some(Vec::new()), + shadows: false, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 83 }), + ..Default::default() + }; + h.ctx.input_mut(|input| input.max_texture_side = 8192); + if !available { + let wire = json!({"integrator":"raytrace","progressive_feedback":true, + "settings":{"width":width,"height":height,"background":background}, + "raytrace":{"primary_samples":1,"lights":[],"shadows":false, + "progressive":{"samples_per_pixel":samples,"seed":83}}}); + assert!(image_params(&h.app).is_err()); + assert!(h.app.run("render.preflight", wire.clone()).is_err()); + assert!(h.app.run("render.start", wire).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.final_partial.is_none()); + eprintln!("MANUAL_FINAL_CPU_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + return None; + } + eprintln!("MANUAL_FINAL_CPU_BRANCH case={case} cpu_supported=true"); + Some(h) + } + + fn actual_final(h: &mut Harness) -> JobHandle { + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + assert!(handle.frame().unwrap().is_some()); + assert!(handle.protected_preview_report().unwrap().is_some()); + handle + } + + // POLICY INPUTS ONLY, not a host-published PartialArc or a while-running receipt. + // Derive bounded display pixels from an actual completed native final, then + // author an explicit source-frontier descriptor to exercise the UI policy. + // No JobHandle, host status, PreviewInfo or GPU executor is fabricated. + fn install_policy_partial(h: &mut Harness, handle: &JobHandle, passes: u32, prefix: u64, sequence: u64) -> interactive::PartialSampling { + use sha2::{Digest, Sha256}; + let status = handle.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + let source = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + let plan = PartialPreviewPlan::new(status.request.width, status.request.height).unwrap(); + let mut pixels = Vec::new(); + for index in 0..usize::try_from(plan.pixels()).unwrap() { + let source_index = plan.source_index(index).unwrap(); + let count = passes + u32::from((source_index as u64) < prefix); + if count == 0 { + pixels.extend_from_slice(&[0, 0, 0, 0]); + } else { + let x = source_index % status.request.width as usize; + let y = source_index / status.request.width as usize; + pixels.extend_from_slice(&source.get_pixel(x as u32, y as u32).0); + } + } + let png = super::partial_png_contract_encode(plan.width(), plan.height(), pixels); + let mut frame_info = frame.info.clone(); + frame_info.width = plan.width(); + frame_info.height = plan.height(); + frame_info.png_bytes = png.len() as u64; + frame_info.png_sha256 = format!("{:x}", Sha256::digest(&png)); + let info = PartialPreviewInfo { + frame: frame_info, + sequence, + source_width: status.request.width, + source_height: status.request.height, + completed_passes: passes, + updated_prefix: prefix, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }; + let covered = vec![0; usize::try_from(plan.pixels()).unwrap()]; // committed misses have zero hit coverage + let expected = interactive::PartialExpectation { + job: handle.id(), + scene_generation: status.scene_generation, + request: &status.request, + final_dimensions: [status.request.width, status.request.height], + }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), covered.len(), None).unwrap().unwrap(); + let image = + interactive::decode_partial_image(&status.request, &info, &png, &covered, sampling, h.ctx.input(|input| input.max_texture_side)).unwrap(); + let texture = h.ctx.load_texture("manual_final_policy_partial", image, egui::TextureOptions::NEAREST); + h.app.render_workspace.final_partial = Some(FinalPartialImage { info, sampling, image: Ok(texture) }); + sampling + } + + #[test] + fn native_manual_final_gui_opt_in_preserves_request_and_promotes_only_real_final() { + let Some(mut h) = fixture(13, 7, 9, [17, 89, 203], "gui_opt_in") else { return }; + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let stored = setups::snapshot(&h.app).unwrap(); + assert!(serde_json::to_value(&stored).unwrap().get("progressive_feedback").is_none()); + let offline = image_request(&h.app).unwrap(); + assert!(offline.get("progressive_feedback").is_none()); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["progressive_feedback"], true); + h.app.render_workspace.view.raytrace.progressive = None; + assert!(image_params(&h.app).unwrap().get("progressive_feedback").is_none()); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 9, seed: 83 }); + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert_eq!(h.app.render_workspace.view.cpu.checked.as_ref().unwrap().request, request); + let handle = actual_final(&mut h); + let status = handle.status().unwrap(); + assert_eq!(serde_json::to_value(&status.request).unwrap(), checked["request"]); + assert_eq!((status.request.width, status.request.height), (13, 7)); + let progressive = status.request.raytrace.as_ref().unwrap().progressive.unwrap(); + assert_eq!((progressive.samples_per_pixel, progressive.seed), (9, 83)); + let image = image::load_from_memory(handle.frame().unwrap().unwrap().png()).unwrap().to_rgba8(); + assert!(image.pixels().all(|pixel| pixel.0 == [17, 89, 203, 255])); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(handle.id())); + assert!(h.app.render_workspace.final_partial.is_none()); + let display = displayed_image(&h.app).unwrap(); + assert!(!display.provisional()); + assert!(display.preview.is_none() && display.partial.is_none()); + assert_eq!(display.logical_size, [13, 7]); + assert_eq!(display.info.job, handle.id()); + assert_eq!(setups::snapshot(&h.app).unwrap(), stored); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[test] + fn native_final_partial_policy_keeps_global_unknown_full_framing_and_real_final_priority() { + let Some(mut h) = fixture(1025, 1, 3, [17, 89, 203], "partial_policy") else { return }; + let handle = actual_final(&mut h); + assert!(h.app.render_workspace.view.completed.is_none()); + // The top-left 1024 representatives are known, but source pixel1024 is not. + let sampling = install_policy_partial(&mut h, &handle, 0, 1024, 1); + assert!(sampling.source_unknown()); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 1024); + let display = displayed_image(&h.app).unwrap(); + assert!(display.provisional() && display.partial.is_some() && display.preview.is_none()); + assert_eq!(display.logical_size, [1025, 1]); + assert_eq!((display.info.width, display.info.height), (1024, 1)); + assert_eq!(display.image.as_ref().unwrap().size(), [1024, 1]); + assert!(reduced_display(&h.app)); + let camera = Camera { distance: 37.0, ..Default::default() }; + h.app.render_workspace.view.result_camera = camera; + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_job = Some(handle.id()); + let report = handle.protected_preview_report().unwrap(); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(handle.id())); + assert!(h.app.render_workspace.final_partial.is_none()); + let display = displayed_image(&h.app).unwrap(); + assert!(!display.provisional()); + assert_eq!(display.logical_size, [1025, 1]); + assert!(!reduced_display(&h.app)); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + invalidate_images(&mut h.app); + assert!(h.app.render_workspace.final_partial.is_none()); + assert_eq!(handle.protected_preview_report().unwrap(), report, "presentation invalidation cannot reset the actual ledger"); + } + + #[test] + fn native_late_complete_policy_preserves_retained_export_then_reconciles_actual_frame() { + let Some(mut h) = fixture(13, 7, 9, [17, 89, 203], "late_complete") else { return }; + let first = actual_final(&mut h); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + let first_bytes = first.frame().unwrap().unwrap().png().to_vec(); + h.app.render_workspace.view.draft.background = [91, 33, 187]; + let second = actual_final(&mut h); + assert_eq!(h.app.render_workspace.view.completed, Some(first.id())); + install_policy_partial(&mut h, &second, 0, 5, 1); + assert!(displayed_image(&h.app).unwrap().provisional()); + let old_path = h.dir.join("manual-final-retained.png"); + let export_job = h.app.render_workspace.view.completed.unwrap(); + h.app.run("render.export", json!({"job":export_job,"path":old_path})).unwrap(); + assert_eq!(std::fs::read(&old_path).unwrap(), first_bytes); + // Regression oracle for the observed event order: + // frame read absent -> later real status Completed -> real frame promoted + // BEFORE provisional clear/fallback. This calls the production policy on + // an actual completed native handle; it does not fake the earlier read. + assert!(!final_job_still_running(&mut h.app, &second)); + assert_eq!(h.app.render_workspace.view.completed, Some(second.id())); + cache_render_images(&mut h.app, &ctx); + assert!(!displayed_image(&h.app).unwrap().provisional()); + assert!(h.app.render_workspace.final_partial.is_none()); + let new_path = h.dir.join("manual-final-current.png"); + let export_job = h.app.render_workspace.view.completed.unwrap(); + h.app.run("render.export", json!({"job":export_job,"path":new_path})).unwrap(); + assert_eq!(std::fs::read(&new_path).unwrap(), second.frame().unwrap().unwrap().png()); + let final_pixels = image::load_from_memory(&std::fs::read(&new_path).unwrap()).unwrap().to_rgba8(); + assert!(final_pixels.pixels().all(|pixel| pixel.0 == [91, 33, 187, 255])); + assert!(!final_job_still_running(&mut h.app, &first), "a different selected final cannot be reconciled through an old handle"); + assert_eq!(h.app.render_workspace.view.completed, Some(second.id())); + } + fn author_box_optics(h: &mut Harness) { + h.app.run("solid.box", json!({"length":200,"width":200,"height":4,"center":[0,0,2],"body_name":"ManualOptics"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.ui.tab = "RENDER".into(); + let view = &mut h.app.render_workspace.view; + view.method = ImageMethod::CpuRaytrace; + view.draft.width = 1; + view.draft.height = 1; + view.draft.background = [255; 3]; + view.draft.stage = Default::default(); + view.draft.surfaces = Default::default(); + assert!(view.draft.stage.is_empty()); + assert!(view.draft.surfaces.is_empty()); + view.transparent = false; + view.draft.exposure_ev = 0.0; + view.raytrace.primary_samples = 1; + view.raytrace.lights = Some(Vec::new()); + view.raytrace.shadows = false; + view.cpu.environment = cpu::Environment::Constant; + view.cpu.color = [1.0; 3]; + view.cpu.intensity = 1.0; + h.app.cam = Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + h.app.cam.set_view(StandardView::Top); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0); + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "ManualOptics").unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.cpu_optics = true; + binding.glass = materials::Glass::recipe("starter.glass.low-iron-clear").unwrap(); + binding.glass.boundary = materials::Boundary::Box; // explicit author choice, not inferred geometry + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + h.app.session.mark_saved(); + } + + fn editor_text(h: &mut Harness, events: Vec) -> String { + fn collect(shape: &egui::Shape, text: &mut String) { + match shape { + egui::Shape::Text(shape) => { + text.push_str(shape.galley.text()); + text.push('\n'); + } + egui::Shape::Vec(shapes) => { + for shape in shapes { + collect(shape, text); + } + } + _ => {} + } + } + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 3200.0))), + events, + ..Default::default() + }, + |ui| { + ui.set_width(420.0); + materials::selection_controls(&mut h.app, ui, Some("ManualOptics")); + }, + ); + let mut text = String::new(); + for clipped in &output.shapes { + collect(&clipped.shape, &mut text); + } + output.textures_delta.clear(); + text + } + + #[test] + fn certification_note_draws_cpu_check_guidance_in_both_sampling_modes_and_legacy_gpu_note() { + let pending: Value = + serde_json::from_str(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pending/cpu-optical-certification.json"))) + .unwrap(); + let key = "render.cpu_optics_certification"; + for locale in ["ar", "de", "en", "es", "he", "ja", "ko", "vi", "zh"] { + assert_eq!(pending[locale].as_object().unwrap().len(), 1); + assert!(!pending[locale][key].as_str().unwrap().trim().is_empty()); + } + let mut h = Harness::new(); + h.ctx.global_style_mut(|style| style.animation_time = 0.0); + author_box_optics(&mut h); + h.app.render_workspace.view.raytrace.progressive = None; + let cpu_note = h.app.tr(key).to_string(); + let gpu_note = h.app.tr("render.material_certification").to_string(); + assert_ne!(cpu_note, key, "a missing catalog fallback is not a translated note"); + assert_ne!(gpu_note, "render.material_certification"); + let document = h.app.session.doc.clone(); + let before = ( + h.app.session.revision, + h.app.session.undo.len(), + h.app.session.is_dirty(), + h.app.render_workspace.view.job, + h.app.render_workspace.view.completed, + ); + let binding_before = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + let initial = editor_text(&mut h, Vec::new()); + if !initial.contains(&cpu_note) { + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + let at = crate::scenario::rect_of(&heading).unwrap().center(); + for pressed in [true, false] { + editor_text( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + } + for progressive in [None, Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 })] { + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = progressive; + let text = editor_text(&mut h, Vec::new()); + assert!(text.contains(&cpu_note), "{text}"); + assert!(!text.contains(&gpu_note), "{text}"); + } + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let text = editor_text(&mut h, Vec::new()); + assert!(text.contains(&gpu_note), "{text}"); + assert!(!text.contains(&cpu_note), "{text}"); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), binding_before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!( + before, + ( + h.app.session.revision, + h.app.session.undo.len(), + h.app.session.is_dirty(), + h.app.render_workspace.view.job, + h.app.render_workspace.view.completed + ) + ); + // Text/layout evidence only: selecting a note never certifies a CPU/GPU render. + } + + #[test] + fn native_progressive_optical_recipe_keeps_authored_ior_certificate_and_final_capture() { + let Some(mut h) = fixture(1, 1, 5, [255; 3], "progressive_optics") else { return }; + author_box_optics(&mut h); + // This optical capture fixture requires normal incidence. StandardView::Top + // intentionally stops short of the pole; author an exact canonical view + // locally, preserving the shared helper's real near-pole GUI path. + h.app.cam = Camera { yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, roll: 0.0, up: solidcraft_engine::render::UpAxis::Z, ..h.app.cam }; + assert!(h.app.cam.is_valid()); + assert_eq!(h.app.cam.fov, 0.0); + assert_eq!(h.app.cam.distance, 10.0); + assert_eq!(h.app.cam.target, solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0)); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (0.0, std::f64::consts::FRAC_PI_2, 0.0, solidcraft_engine::render::UpAxis::Z) + ); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 }); + // The orthographic pixel's entire jitter support lies in +/-4mm, + // strictly inside the independently authored +/-100mm box footprint. + assert_eq!(h.app.cam.half_height(), 4.0); + for (x, y) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] { + let (origin, direction) = h.app.cam.ray(x, y, 1.0, 1.0); + assert!(direction.x.abs() < 1e-12 && direction.y.abs() < 1e-12); + assert!((direction.z.abs() - 1.0).abs() < 1e-12); + let point = origin + direction * ((4.0 - origin.z) / direction.z); + assert!(point.x.abs() <= 4.0 + 1e-9 && point.y.abs() <= 4.0 + 1e-9); + assert!(point.x.abs() < 100.0 && point.y.abs() < 100.0); + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let binding_before = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["progressive_feedback"], true); + let optics = &request["raytrace"]["dielectrics"][0]; + assert_eq!(optics["body_name"], "ManualOptics"); + assert_eq!(optics["boundary"], "closed_box"); + assert_eq!(optics["ior"], 1.5, "the production recipe IOR is not reduced for this case"); + for (index, transmission) in [0.98_f64, 0.99, 1.0].into_iter().enumerate() { + let expected = -transmission.ln() / 4.0; + assert!((optics["absorption_per_mm"][index].as_f64().unwrap() - expected).abs() < 1e-15); + } + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + let handle = actual_final(&mut h); + let status = handle.status().unwrap(); + assert_eq!(serde_json::to_value(&status.request).unwrap(), checked["request"]); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + assert!(!status.options.nested_media); + let frame = handle.frame().unwrap().unwrap(); + let pixels = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (1, 1)); + let pixel = pixels.get_pixel(0, 0).0; + assert_eq!(pixel[3], 255); + assert!(pixel[..3].iter().any(|value| *value > 0)); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), binding_before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + // Actual CPU capture/completion + nonblack optical smoke, not a full + // Fresnel/TIR oracle or a partial-optical-tree while-running receipt. + } +} + +// These exercise GUI navigation against the real cooperative Raster host. +// They do not qualify CPU raytracing, progressive cadence or GPU rendering. +fn auto_result_raster_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":3,"width":4,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.render_workspace.view.draft.width = 13; + h.app.render_workspace.view.draft.height = 7; + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h +} + +#[test] +fn auto_result_success_opens_once_and_explicit_model_survives_real_completion() { + use solidcraft_engine::render::job::Phase; + let mut h = auto_result_raster_fixture(); + assert!(h.app.preferences.render_open_result_on_start); + assert!(!h.app.render_workspace.view.result); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert!(h.app.render_workspace.view.result); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + assert!(handle.frame().unwrap().is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(ribbon::action_ready(&h.app, "render.export").is_err()); + let request = handle.status().unwrap().request; + assert_eq!((request.width, request.height, request.integrator), (13, 7, Integrator::Raster)); + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.result); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + assert!(!h.app.render_workspace.view.result); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result, "publication/repaint must respect an explicit Model selection"); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().expect("bounded cooperative Raster work must complete"); + assert_eq!((frame.info.width, frame.info.height), (13, 7)); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + assert!(ribbon::action_ready(&h.app, "render.export").is_ok()); + for _ in 0..3 { + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera); +} + +#[test] +fn auto_result_disabled_keeps_both_selected_views_through_start_and_completion() { + for selected in [false, true] { + let mut h = auto_result_raster_fixture(); + crate::prefs::set(&mut h.app, &json!({"render_open_result_on_start":false})).unwrap(); + h.app.run("render.result.view", json!({"view":if selected {"image"} else {"model"}})).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + assert_eq!(h.app.render_workspace.view.result, selected); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert!(handle.frame().unwrap().is_none()); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + if handle.frame().unwrap().is_some() { + break; + } + } + assert!(handle.frame().unwrap().is_some(), "bounded cooperative Raster work must complete"); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + } +} + +#[test] +fn auto_result_check_invalid_start_and_real_queue_full_preserve_selected_view() { + use solidcraft_engine::render::job::Phase; + for selected in [false, true] { + let mut h = auto_result_raster_fixture(); + assert!(h.app.preferences.render_open_result_on_start); + h.app.run("render.result.view", json!({"view":if selected {"image"} else {"model"}})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(h.app.render_workspace.view.job.is_none()); + h.app.render_workspace.view.draft.width = 0; + assert!(ribbon::perform_job(&mut h.app, "render.preflight").is_err()); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(ribbon::perform_job(&mut h.app, "render.start").is_err()); + assert_eq!(h.app.render_workspace.view.result, selected); + h.app.render_workspace.view.draft.width = 13; + let request = image_params(&h.app).unwrap(); + let mut jobs = Vec::new(); + // Queue two real jobs without registering a GUI job. + // No pump or worker thread runs between admission and the third Start. + for _ in 0..2 { + let reply = h.app.session.execute("render.start", &request).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + jobs.push(handle); + } + ribbon::action_ready(&h.app, "render.start").unwrap(); + let error = ribbon::perform_job(&mut h.app, "render.start").unwrap_err(); + assert!(error.contains("this document already has an active and pending render"), "expected real document QueueFull: {error}"); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + for handle in jobs { + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + assert!(handle.frame().unwrap().is_none()); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + } +} + +#[test] +fn product_preview_exposure_is_bounded_without_rewriting_method_or_advanced_intent() { + let mut h = Harness::new(); + h.app.render_workspace.view.samples = 512; + h.app.render_workspace.view.max_depth = 8; + h.app.render_workspace.view.seed = 42; + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.shadows = false; + let cpu = serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(); + let gpu = (h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len()); + let camera = h.app.cam; + for ev in [-32.0, -3.5, -0.0, 0.0, 1.75, 32.0] { + h.app.render_workspace.view.draft.exposure_ev = ev; + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::Raster] { + select_image_method(&mut h.app, method); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, ev, "method selection cannot silently reset saved exposure intent"); + let preview = product_preview_exposure(&h.app).unwrap(); + // Model uses the common EV for every final method, even with Interactive Off. + // This intentionally supersedes this unpublished test's Raster-only helper contract. + assert_eq!(preview.ev(), ev as f32); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(), cpu); + assert_eq!((h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed), gpu); + } + } + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::Raster] { + select_image_method(&mut h.app, method); + for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -32.001, 32.001] { + h.app.render_workspace.view.draft.exposure_ev = invalid; + let error = product_preview_exposure(&h.app).unwrap_err(); + assert_eq!(error, h.app.tr("render.product_exposure_invalid")); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev.to_bits(), invalid.to_bits(), "a refusal must not clamp or replace intent"); + // The real Model show route must report the typed exposure refusal before + // its no-GPU fallback, without starting a final or Interactive capture. + let mut output = h.ctx.run_ui(Default::default(), |ui| show(&mut h.app, ui)); + assert!(crate::test_support::text_shapes(&output).any(|shape| shape.galley.text() == error)); + output.textures_delta.clear(); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), history); + assert_eq!(h.app.cam, camera); +} + +#[test] +fn raster_shot_exposure_uses_the_existing_slider_and_one_undoable_saved_command() { + let mut h = frame_editor_fixture(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Exposure subject"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + select_image_method(&mut h.app, ImageMethod::Raster); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0); + let before = h.app.session.doc.to_json(); + let camera = h.app.cam; + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.75, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert!(saved.exposure_ev.is_finite() && saved.exposure_ev > 0.0 && saved.exposure_ev <= 32.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, saved.exposure_ev); + assert_eq!(product_preview_exposure(&h.app).unwrap().ev(), saved.exposure_ev as f32); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + #[cfg(not(target_arch = "wasm32"))] + { + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let (_, geometry) = gpu_scene(&scene).unwrap(); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye().to_f32(); + let capture = |exposure| { + crate::gpu::render_product_offscreen_exposure( + geometry.clone(), + None, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], if camera.fov > 0.0 { 1.0 } else { 0.0 }], + 64, + false, + exposure, + ) + }; + if let Some(zero) = capture(Default::default()) { + let exposed = capture(product_preview_exposure(&h.app).unwrap()).expect("the same supported capture route must complete"); + assert_ne!(exposed, zero, "saved GUI exposure must reach actual product-shader pixels"); + assert_eq!(&exposed[..4], &zero[..4], "the capture backplate is not exposed"); + assert_eq!(capture(Default::default()).unwrap(), zero, "returning to zero restores the exact captured response"); + eprintln!("RASTER_GUI_EXPOSURE_CAPTURE supported=true"); + } else { + assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GUI product capture is unavailable"); + eprintln!("RASTER_GUI_EXPOSURE_CAPTURE supported=false"); + } + } + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +// Original F1 regressions: real native accepted pixels, no injected cache/frame. +// This first alignment block covers accepted camera and framing, not a new +// proof of all possible scene/placement/visibility changes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_known_image_after_finished_pan_blocks_current_camera_targets_but_keeps_navigation_and_escape() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_known_image_after_finished_pan_blocks_current_camera_targets_but_keeps_navigation_and_escape") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + let handle = interactive::test_current(&h.app).unwrap().unwrap(); + let (accepted, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((accepted.job, samples, complete), (job, 16, true)); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let end = at + egui::vec2(28.0, 12.0); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed: true, modifiers: egui::Modifiers::NONE }, + ], + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(end)]); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: end, button: egui::PointerButton::Middle, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert_ne!(h.app.cam.target, camera.target, "the real shared middle-pan must have moved the camera"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert!(!interactive::awaiting_current_frame(&h.app), "this is known paused evidence, not the existing blank/Unknown guard"); + assert!(interactive::blocks_geometry_input(&h.app)); + let viewport = h.app.viewport.rect.unwrap(); + let geometry_rect = interactive::geometry_input_rect(&h.app, viewport); + let projection = crate::viewport::projection(&h.app, geometry_rect); + let current_hit = projection.to_screen(camera.target).unwrap(); + assert!(geometry_rect.contains(current_hit)); + assert!( + crate::viewport::pick(&h.app, &projection, current_hit) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject") }), + "prove there really is a current-camera target for the new guard to reject" + ); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none() && h.app.session.selection.is_empty()); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none()); + assign::arm(&mut h.app, json!({"appearance":"ABS - Red"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + let (retained, retained_samples, retained_complete, retained_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (retained.job, retained.png_sha256, retained_samples, retained_complete, retained_texture), + (job, accepted.png_sha256, samples, complete, texture) + ); + let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.01, false, true); + assert!(painted, "the retained image stays visible as a reference"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + interactive_assert_final_export_isolation(&mut h, &handle); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_aligned_known_image_supports_repeated_material_edits_and_uses_its_painted_rectangle() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_aligned_known_image_supports_repeated_material_edits_and_uses_its_painted_rectangle") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + let viewport = h.app.viewport.rect.unwrap(); + let pixels = interactive::geometry_input_rect(&h.app, viewport); + assert!(pixels.width() < viewport.width(), "the original square image is letterboxed in this landscape viewport"); + assert!((pixels.width() - pixels.height()).abs() <= f32::EPSILON * pixels.height().max(1.0)); + let undo = h.app.session.undo.len(); + for (index, name) in ["ABS - Blue", "ABS - Red"].into_iter().enumerate() { + assert!(!interactive::blocks_geometry_input(&h.app), "Pause alone and an earlier appearance edit cannot block aligned input"); + assign::arm(&mut h.app, json!({"appearance":name})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Subject"].name, name); + assert_eq!(h.app.cam, camera); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!interactive::blocks_geometry_input(&h.app)); + } + assign::stop(&mut h.app); + let selection = h.app.session.selection.clone(); + let outside_pixels = egui::pos2(viewport.left() + 1.0, viewport.center().y); + assert!(!pixels.contains(outside_pixels)); + interactive_canvas_input_click(&mut h, &mut time, outside_pixels, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none()); + assert_eq!(h.app.session.selection, selection, "letterbox margins are not pixel-aligned CAD targets"); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_known_image_rejects_authored_aspect_change_without_blanket_pause_or_final_gate() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_known_image_rejects_authored_aspect_change_without_blanket_pause_or_final_gate") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + let width = h.app.render_workspace.view.draft.width; + assert!(!interactive::blocks_geometry_input(&h.app)); + let document = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "start a real drag against aligned accepted pixels"); + h.app.render_workspace.view.draft.width = width * 2; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app)); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_none() && assign::hover(&h.app).is_none()); + assert!(!assign::cancel(&mut h.app), "the blocked release must drain the real drag"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!( + (h.app.session.revision, h.app.session.undo.len()), + (revision, undo), + "the guard must stop a framing-only drag without relying on the document revision guard" + ); + h.app.render_workspace.view.draft.width = width; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(!interactive::blocks_geometry_input(&h.app), "restoring the accepted aspect restores aligned same-camera input"); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app), "the manual Result path owns its own camera and input policy"); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::awaiting_current_frame(&h.app) && interactive::blocks_geometry_input(&h.app)); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +// Geometry/placement/visibility successor: original native snapshots and CAD +// commands only. No injected publications, host factory or scheduling barrier. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_camera_geometry_move_rejects_real_new_targets_and_preserves_old_pixels() { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_camera_geometry_move_rejects_real_new_targets_and_preserves_old_pixels") + else { + return; + }; + let world = h.app.session.interactive_cached_world_state().unwrap(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + let retained = interactive::test_cache(&h.app).unwrap(); + assert_eq!((retained.0.job, retained.1, retained.2), (job, 16, true)); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("solid.move", json!({"bodies":["Subject"],"translate":[2,0,0]})).unwrap(); + let moved = h.app.session.interactive_cached_world_state().unwrap(); + assert!(!Arc::ptr_eq(&world, &moved)); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "must reject before observed is refreshed, using accepted capture authority"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let center = moved.body("Subject").unwrap().mesh().bounds().center(); + let at = projection.to_screen(center).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject") }) + ); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none()); + assert_eq!(h.app.session.selection, selection); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none()); + assign::arm(&mut h.app, json!({"appearance":"ABS - Red"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let after = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (after.0.job, after.0.png_sha256, after.1, after.2, after.3), + (retained.0.job, retained.0.png_sha256, retained.1, retained.2, retained.3) + ); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert!(!h.app.render_workspace.interactive.pending()); + assign::stop(&mut h.app); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_world_visibility_restore_keeps_selection_and_repeated_material_edits_aligned() { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_world_visibility_restore_keeps_selection_and_repeated_material_edits_aligned") + else { + return; + }; + h.app.run("solid.box", json!({"length":6,"width":6,"height":4,"center":[22,0,2],"body_name":"Other"})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + let world = h.app.session.interactive_cached_world_state().unwrap(); + let camera = h.app.cam; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("browser.visibility", json!({"items":["Subject"],"visible":false})).unwrap(); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "unchanged world alone cannot certify a changed visible body set"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let at = projection.to_screen(world.body("Other").unwrap().mesh().bounds().center()).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Other") }), + "a still-visible current-world target exists" + ); + let selection = h.app.session.selection.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.selection, selection); + assert!(h.app.viewport.hover.is_none()); + h.app.run("browser.visibility", json!({"items":["Subject"],"visible":true})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(!interactive::blocks_geometry_input(&h.app), "restoring the exact accepted visibility can restore alignment without recapture"); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Other".into() })); + assert!(!interactive::blocks_geometry_input(&h.app), "selection is not a scene invalidation"); + let undo = h.app.session.undo.len(); + for (index, name) in ["ABS - Blue", "ABS - Red"].into_iter().enumerate() { + assign::arm(&mut h.app, json!({"appearance":name})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.doc.appearances.bodies["Other"].name, name); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + assert!(!interactive::blocks_geometry_input(&h.app), "render-only refresh must keep the accepted geometric identity usable"); + } + assert_eq!(h.app.cam, camera); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!h.app.render_workspace.interactive.pending()); + assign::stop(&mut h.app); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_camera_occurrence_capture_and_pending_move_require_new_accepted_world() { + for capture in [true, false] { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_camera_occurrence_capture_and_pending_move_require_new_accepted_world") + else { + return; + }; + let component = h.app.run("component.create", json!({"name":"AlignmentPart","grounded":false})).unwrap(); + h.app.run("solid.box", json!({"length":6,"width":6,"height":4,"body_name":"Placed"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[20,0,0]})).unwrap(); + let world = h.app.session.world_state(); // Explicit real test preparation, never performed by the guard. + let placed = world.bodies.iter().find(|body| body.name != "Subject").unwrap().name.clone(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[3,0,0],"capture":capture})).unwrap(); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "a missing/stale prepared world is not accepted-scene authority"); + let moved = h.app.session.world_state(); // Warm through the ordinary API only in the original test. + assert!(!Arc::ptr_eq(&world, &moved)); + assert!(interactive::blocks_geometry_input(&h.app), "warming a new current world must not bless the old accepted pixels"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let at = projection.to_screen(moved.body(&placed).unwrap().mesh().bounds().center()).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == &placed) }) + ); + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.selection, selection); + assert!(h.app.viewport.hover.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let new_job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + assert_ne!(new_job, job); + assert!(!interactive::blocks_geometry_input(&h.app), "only the new accepted capture can establish the moved scene"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +// Common Model EV must stop at captured-image boundaries; these use real producers. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn product_preview_exposure_does_not_regrade_a_real_native_cpu_interactive_png() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "product_preview_exposure_does_not_regrade_a_real_native_cpu_interactive_png") { + return; + } + assert!(h.app.viewport.gpu.is_none(), "real show has no product-GPU fallback in this fixture"); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, false); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let status = held.job.status().unwrap(); + assert_eq!(status.request.raster_exposure_ev, 0.0, "CPU request must not gain a second Raster EV"); + assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, 1.0); + let frame = held.job.frame().unwrap().unwrap(); + let original = frame.png().to_vec(); + held.sender.send(held.reply).unwrap(); + let (mut accepted, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + let texture = interactive::test_cache(&h.app).unwrap().3; + let uploaded = &accepted.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(&original, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [16, 16]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + accepted.textures_delta.clear(); + + // Current capture first, then a paused image after a different common EV edit. + // Both must paint their captured texture, without entering the live Model branch. + for (step, ev) in [1.0, 2.0].into_iter().enumerate() { + if step == 1 { + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.draft.exposure_ev = ev; + } + assert_eq!(product_preview_exposure(&h.app).unwrap().ev(), ev as f32); + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.4 + step as f64 * 0.1), + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + assert!(!crate::test_support::text_shapes(&output).any(|s| s.galley.text() == h.app.tr("render.error_gpu_preview"))); + assert!(!output.textures_delta.set.contains_key(&texture), "captured PNG is not uploaded or graded again"); + output.textures_delta.clear(); + assert!( + h.ctx.tessellate(output.shapes, output.pixels_per_point).iter().any( + |shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == texture && !mesh.indices.is_empty()) + ) + ); + let (cached, samples, complete, id) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, cached.png_sha256, samples, complete, id), (held.job.id(), frame.info.png_sha256.clone(), 16, true, texture)); + assert_eq!(held.job.frame().unwrap().unwrap().png(), original.as_slice()); + assert!(!h.app.render_workspace.interactive.pending(), "show must not dispatch a replacement capture"); + interactive_assert_final_export_isolation(&mut h, &held.job); + } + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn product_preview_exposure_does_not_regrade_or_validate_a_retained_real_result() { + let mut h = auto_result_raster_fixture(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().expect("bounded real cooperative Raster result"); + let original = frame.png().to_vec(); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + let mut texture = None; + for ev in [1.0, -1.0, f64::NAN] { + h.app.render_workspace.view.draft.exposure_ev = ev; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }, + |ui| show(&mut h.app, ui), + ); + assert!(h.app.render_workspace.view.result); + let id = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + if let Some(prior) = texture { + assert_eq!(id, prior); + assert!(!output.textures_delta.set.contains_key(&id)); + } else { + let uploaded = &output.textures_delta.set.get(&id).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(&original, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [13, 7]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels + .pixels + .iter() + .zip(png.pixels()) + .all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + } + texture = Some(id); + assert!(!crate::test_support::text_shapes(&output).any(|s| s.galley.text() == h.app.tr("render.product_exposure_invalid"))); + output.textures_delta.clear(); + assert!( + h.ctx + .tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id && !mesh.indices.is_empty())) + ); + assert_eq!(handle.frame().unwrap().unwrap().png(), original.as_slice()); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + } + let path = h.dir.join("common-model-ev-retained-result.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), original); +} + +#[test] +fn editing_an_inactive_selected_shot_keeps_the_active_setup_draft_and_camera() { + let mut h = frame_editor_fixture(); + assert_eq!(shot::selected(&h.app), Some("Hero")); + assert_eq!(h.app.render_workspace.view.name, "Studio", "selection does not activate a saved setup"); + let active = serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(); + let camera = h.app.cam; + let before = h.app.session.doc.to_json(); + let studio = h.app.session.doc.render.setups.get("Studio").cloned(); + let mut expected_hero = h.app.session.doc.render.setups["Hero"].clone(); + expected_hero.exposure_ev = 1.5; + let undo = h.app.session.undo.len(); + shot::edit_settings(&mut h.app, "Hero", json!({"exposure_ev":1.5})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Hero"], expected_hero); + assert_eq!(h.app.session.doc.render.setups.get("Studio").cloned(), studio); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), active); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1, "only the saved Hero edit enters history"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), active); + assert_eq!(h.app.cam, camera); +} + +// Integration of the common ±32 EV contract with the existing Shot editor. +// This exercises egui input and the saved command, without opening a GPU device. +#[test] +fn cpu_shot_exposure_reaches_extended_range_via_slider_and_one_saved_command() { + let mut h = frame_editor_fixture(); + h.app.run("render.settings.set", json!({"name":"Hero","set":{"job":{"method":"cpu_raytrace"},"exposure_ev":0.0}})).unwrap(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0); + let before = h.app.session.doc.to_json(); + let camera = h.app.cam; + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.875, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert!(saved.exposure_ev.is_finite() && saved.exposure_ev > 16.0 && saved.exposure_ev <= 32.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, saved.exposure_ev); + // The shared production constructor captures portable intent without host admission. + assert!(!setups::has_runtime_inputs(&h.app)); + assert_eq!(image_request(&h.app).unwrap()["settings"]["exposure_ev"], json!(saved.exposure_ev)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +// Explicit catalogue staging, not a scalar appearance assignment or transport oracle. +mod glass_library_bridge { + use super::*; + use solidcraft_engine::{ + Sel, + doc::appearance_pack::{Recipe, STARTER_PACK}, + }; + + fn fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":4,"body_name":"Optics"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Optics".into() }]})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.stage = Stage::Look; + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 64; + h.app.render_workspace.view.transparent = false; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.session.mark_saved(); + h + } + + #[test] + fn library_bridge_stages_all_six_authored_recipes_without_cpu_permission_or_design_changes() { + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let mut h = fixture(); + let doc = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let options = serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(); + library::stage_glass(&mut h.app, preset.id).unwrap(); + let binding = &h.app.render_workspace.view.materials.bindings[0]; + assert_eq!(binding.target.name, "Optics"); + assert!(binding.target.stable_target.is_some()); + assert!(binding.glass_enabled && !binding.cpu_optics && !binding.maps_enabled && !binding.coat_enabled); + assert_eq!(binding.glass.recipe, Some(preset.id)); + assert_eq!(binding.glass.ior, recipe.dielectric_ior); + for (sigma, transmission) in binding.glass.absorption.into_iter().zip(recipe.transmission_linear_rgb) { + assert!(((-sigma * recipe.reference_path_mm).exp() - transmission).abs() < 1e-12); + } + match recipe.boundary { + solidcraft_engine::doc::appearance_pack::GlassBoundary::Closed => { + assert_eq!(binding.glass.boundary, materials::Boundary::Closed); + assert!(!binding.glass.shadows); + } + solidcraft_engine::doc::appearance_pack::GlassBoundary::Thin { thickness_mm } => { + assert_eq!(binding.glass.boundary, materials::Boundary::Thin); + assert_eq!(binding.glass.thickness, thickness_mm); + assert!(binding.glass.shadows, "preparing a Thin recipe is not consent to remove transmitted shadows"); + } + } + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(), options); + assert!(runtime_image_request(&h.app, false).is_err(), "CPU permission is still explicit"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + assert!(matches!(&h.app.render_workspace.view.selection, RenderSelection::Object(items) if items == &h.app.session.selection)); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Appearance); + assert_eq!(h.app.status.as_ref().unwrap().0, h.app.tr("render.glass_library_prepared")); + assert_ne!(h.app.status.as_ref().unwrap().0, h.app.tr("render.library_applied")); + count += 1; + } + assert_eq!(count, 6); + } + + #[test] + fn library_bridge_requires_stable_glass_id_and_keeps_scalar_assignment_guards() { + let mut h = fixture(); + let opaque = STARTER_PACK.iter().find(|p| matches!(p.recipe, Recipe::Opaque(_))).unwrap(); + for id in ["Glass - Clear", "Glass Recipe - Low Iron Clear", opaque.id, "starter.glass.not-a-recipe"] { + assert!(library::stage_glass(&mut h.app, id).is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + } + let catalog = h.app.run("appearance.library", json!({})).unwrap(); + let glass = catalog["appearances"].as_array().unwrap().iter().find(|p| p["id"] == "starter.glass.low-iron-clear").unwrap(); + assert_eq!(glass["available"], false); + for appearance in ["starter.glass.low-iron-clear", "Glass Recipe - Low Iron Clear"] { + assert!(h.app.run("appearance.assign", json!({"bodies":["Optics"],"appearance":appearance,"color":"#ffffff","opacity":1.0})).is_err()); + } + h.app.run("appearance.assign", json!({"bodies":["Optics"],"appearance":"Glass - Clear"})).unwrap(); + assert!(h.app.session.doc.appearances.bodies["Optics"].opacity < 1.0); + assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "legacy alpha is never promoted to physical glass"); + } + + #[test] + fn library_bridge_refuses_face_component_empty_multiple_and_raster_targets() { + let mut h = fixture(); + h.app.run("select.filter", json!({"mode":"face"})).unwrap(); + let hit = crate::viewport::Hit::Face { body: "Optics".into(), index: 0, point: solidcraft_engine::geom::Vec3::ZERO }; + let face = crate::viewport::candidate(&h.app, &[hit]).unwrap().1; + assert!(matches!(face, Sel::Face { .. })); + let component = h.app.run("component.create", json!({"name":"Unassigned component"})).unwrap(); + let occurrence = component["occurrence"].as_u64().unwrap(); + for selection in [ + vec![], + vec![face], + vec![Sel::Occurrence { path: vec![occurrence] }], + vec![Sel::Body { name: "Optics".into() }, Sel::Body { name: "Optics".into() }], + ] { + h.app.session.selection = selection; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + } + h.app.session.selection = vec![Sel::Body { name: "Optics".into() }]; + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + } + + #[test] + fn library_bridge_hidden_stale_document_and_changed_target_never_refresh_a_binding() { + let mut h = fixture(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + h.app.session.visibility.hidden_bodies.clear(); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings[0].target.ordinal += 1; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].target.ordinal, original.target.ordinal + 1); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.session.doc = Arc::new((*h.app.session.doc).clone()); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + h.app.render_workspace.view.materials.bindings[0] = original; + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err(), "CAD revision is not silently revalidated"); + } + + #[test] + fn library_bridge_conflicts_preserve_permission_shadows_scattering_and_other_material_intent() { + for conflict in 0..4 { + let mut h = fixture(); + library::stage_glass(&mut h.app, "starter.glass.thin-clear").unwrap(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.cpu_optics = true; + match conflict { + 0 => binding.coat_enabled = true, + 1 => binding.maps_enabled = true, + 2 => { + binding.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }) + } + _ => binding.glass.ior = 1.7, + } + let before = format!("{:?}", h.app.render_workspace.view.materials); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + } + } + + #[test] + fn library_bridge_exact_repeat_preserves_existing_cpu_permission_disabled_state_and_values() { + let mut h = fixture(); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + h.app.render_workspace.view.materials.bindings[0].enabled = false; + h.app.render_workspace.view.materials.enabled = false; + let before = format!("{:?}", h.app.render_workspace.view.materials); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 1); + } + + #[test] + fn library_bridge_respects_authoring_and_cpu_target_caps_without_activating_other_bindings() { + for (method, count, active) in [(ImageMethod::GpuRaytrace, 128, false), (ImageMethod::CpuRaytrace, 8, true)] { + let mut h = fixture(); + h.app.render_workspace.view.method = method; + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|t| t.name == "Optics").unwrap(); + for i in 0..count { + let mut other = target.clone(); + other.name = format!("Other{i}"); + let mut binding = materials::Binding::new(other, &h.app); + binding.glass_enabled = active; + h.app.render_workspace.view.materials.bindings.push(binding); + } + let before = format!("{:?}", h.app.render_workspace.view.materials); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + } + } + + #[test] + fn library_bridge_keeps_closed_thin_and_strict_cpu_choices_explicit_without_a_transport_claim() { + let mut h = fixture(); + h.app.render_workspace.view.raytrace.dielectric_transport = solidcraft_engine::render::job::CpuDielectricTransport::StrictTir; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [0.25, 0.5, 0.75]; + h.app.render_workspace.view.cpu.intensity = 2.0; + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + assert!(runtime_image_request(&h.app, false).is_err(), "Closed is not silently certified Box"); + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Box; + let wire = runtime_image_request(&h.app, false).unwrap(); + assert_eq!(wire["raytrace"]["dielectric_transport"], "strict_tir"); + assert_eq!(wire["raytrace"]["dielectrics"][0]["ior"], 1.5); + assert_eq!(wire["raytrace"]["dielectrics"][0]["boundary"], "closed_box"); + assert_eq!(wire["raytrace"]["exposure_ev"], 1.25); + assert_eq!(wire["settings"]["exposure_ev"], 0.0); + assert_eq!(wire["raytrace"]["environment"]["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(wire["raytrace"]["environment"]["intensity"], 2.0); + assert!(setups::snapshot(&h.app).is_err(), "transient staging never becomes saved CPU optics"); + // This checks routing only. A real StrictTir LimitExceeded remains FAIL for G02-C. + } + + #[test] + fn clicked_library_glass_action_reaches_existing_body_editor_and_never_reports_applied() { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + let mut view = std::mem::take(&mut h.app.render_workspace.view.library); + library::choose(&mut h.app, &mut view, "appearances", "starter.glass.low-iron-clear").unwrap(); + h.app.render_workspace.view.library = view; + h.frames(3); + let doc = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:library:prepare-glass"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 1); + assert!(!h.app.render_workspace.view.materials.bindings[0].cpu_optics); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Appearance); + assert!( + matches!(&h.app.render_workspace.view.selection, RenderSelection::Object(items) if matches!(items.as_slice(), [Sel::Body {name}] if name == "Optics")) + ); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.status.as_ref().unwrap().0, h.app.tr("render.glass_library_prepared")); + assert_ne!(h.app.status.as_ref().unwrap().0, h.app.tr("render.library_applied")); + } + + #[test] + fn library_bridge_messages_cover_every_current_delivered_locale() { + let messages: Value = serde_json::from_str(include_str!("../../../assets/locales/pending/render-glass-library-route.json")).unwrap(); + for locale in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + for id in [ + "render.glass_library_conflict", + "render.glass_library_edit", + "render.glass_library_help", + "render.glass_library_method", + "render.glass_library_prepared", + ] { + assert!(messages[locale][id].as_str().is_some_and(|s| !s.is_empty()), "{locale}/{id}"); + } + } + } +} diff --git a/proposals/render/2026-10-31/cpu-directional-shadow-ui/delta.patch b/proposals/render/2026-10-31/cpu-directional-shadow-ui/delta.patch new file mode 100644 index 000000000..e95bf4974 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-directional-shadow-ui/delta.patch @@ -0,0 +1,327 @@ +--- a/crates/ui-egui/src/render_workspace_materials.rs ++++ b/crates/ui-egui/src/render_workspace_materials.rs +@@ -346,6 +346,7 @@ + if count > 8 { + return Err(app.tr("render.cpu_optics_limit").into()); + } ++ let mut shadow_transmission = None; + for binding in view.materials.bindings.iter().filter(|binding| binding.active()) { + if !binding.cpu_optics { + return Err(app.tr("render.cpu_optics_explicit").into()); +@@ -353,6 +354,24 @@ + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } ++ if shadow_transmission.is_some_and(|selected| selected != binding.glass.shadows) { ++ return Err(app.tr("render.cpu_shadow_mixed").into()); ++ } ++ shadow_transmission = Some(binding.glass.shadows); ++ } ++ // The current producer has one global directional switch, not a per-body mask. ++ // Never erase an OFF assignment or change the separate global shadows control. ++ let shadow_transmission = shadow_transmission.unwrap_or(false); ++ if options.directional_shadow_transmission && !shadow_transmission { ++ return Err(app.tr("render.cpu_shadow_conflict").into()); ++ } ++ if shadow_transmission ++ && (!options.shadows ++ || options.environment.is_some() ++ || params.get("environment").is_some_and(|value| !value.is_null()) ++ || view.cpu.nested_media) ++ { ++ return Err(app.tr("render.cpu_optics_unsupported").into()); + } + // Match the same placement identity that render.scene used for selection. + // No mesh extraction/certificate/proxy is performed on the UI thread. +@@ -385,7 +404,7 @@ + { + return Err(app.tr("render.material_target_missing").into()); + } +- if !binding.glass_enabled || binding.coat_enabled || binding.maps_enabled || binding.glass.shadows || binding.glass.subsurface.is_some() { ++ if !binding.glass_enabled || binding.coat_enabled || binding.maps_enabled || binding.glass.subsurface.is_some() { + return Err(app.tr("render.cpu_optics_unsupported").into()); + } + let boundary = match binding.glass.boundary { +@@ -403,6 +422,7 @@ + }); + } + options.dielectrics = dielectrics; ++ options.directional_shadow_transmission = shadow_transmission; + // The composed typed request, not the editor's sampling label, decides + // sampling compatibility. Progressive optics requires the separately + // reviewed producer; geometry and installed capability still need admission. +@@ -634,7 +654,7 @@ + let nested_label = app.tr("render.children.nested").to_owned(); + let response = ui_kit::checkbox(ui, &nested_label, &mut app.render_workspace.view.cpu.nested_media); + crate::scenario::publish_target("render:cpu-optics-nested", response.rect); +- note(app, ui, "render.cpu_optics_help"); ++ note(app, ui, "render.cpu_directional_shadow_help"); + } + note(app, ui, "render.appearance_editor.glass_note"); + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { +--- a/crates/ui-egui/src/render_workspace_tests.rs ++++ b/crates/ui-egui/src/render_workspace_tests.rs +@@ -8923,6 +8923,193 @@ + runtime_image_request(&h.app, false).unwrap() + } + ++ fn directional_shadow_fixture(choices: &[bool]) -> Harness { ++ use solidcraft_engine::render::job::DirectionalLightOptions; ++ assert!(!choices.is_empty() && choices.len() <= 2); ++ let mut h = Harness::new(); ++ for index in 0..choices.len() { ++ h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"center":[index as f64 * 4.0,0,2],"body_name":format!("Shadow{index}")})).unwrap(); ++ } ++ h.app.run("render.scene", json!({})).unwrap(); ++ h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; ++ h.app.render_workspace.view.raytrace.shadows = true; ++ h.app.render_workspace.view.raytrace.lights = ++ Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 2.0 }]); ++ h.app.render_workspace.view.draft.width = 1; ++ h.app.render_workspace.view.draft.height = 1; ++ h.app.render_workspace.view.draft.exposure_ev = 1.25; ++ h.app.render_workspace.view.materials.enabled = true; ++ let targets = materials::read_targets(&mut h.app).unwrap(); ++ for (index, shadows) in choices.iter().copied().enumerate() { ++ let target = targets.iter().find(|target| target.name == format!("Shadow{index}")).unwrap().clone(); ++ let mut binding = materials::Binding::new(target, &h.app); ++ binding.cpu_optics = true; ++ binding.glass_enabled = true; ++ binding.glass.boundary = materials::Boundary::Box; ++ binding.glass.shadows = shadows; ++ h.app.render_workspace.view.materials.bindings.push(binding); ++ } ++ h.app.session.mark_saved(); ++ h ++ } ++ ++ fn directional_shadow_refusal_is_atomic(h: &Harness, key: Option<&str>) { ++ let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"preserve"}); ++ cpu::params(&h.app, &mut request).unwrap(); ++ let before = request.clone(); ++ let authored = format!("{:?}", h.app.render_workspace.view.materials); ++ let options = json!(h.app.render_workspace.view.raytrace); ++ let error = materials::params(&h.app, &mut request).unwrap_err(); ++ if let Some(key) = key { ++ assert!(error.contains(h.app.tr(key)), "{key}: {error}"); ++ } ++ assert_eq!(request, before); ++ assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); ++ assert_eq!(json!(h.app.render_workspace.view.raytrace), options); ++ } ++ ++ #[test] ++ fn cpu_directional_shadow_uniform_assignments_lower_typed_wire_without_changing_authored_options() { ++ use solidcraft_engine::render::job::{CpuDielectricTransport, CpuProgressiveOptions, RaytraceOptions}; ++ for shadows in [false, true] { ++ for progressive in [false, true] { ++ for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { ++ let mut h = directional_shadow_fixture(&[shadows, shadows]); ++ h.app.render_workspace.view.raytrace.dielectric_transport = policy; ++ h.app.render_workspace.view.raytrace.progressive = progressive.then_some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 411 }); ++ let document = h.app.session.doc.clone(); ++ let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); ++ let authored = format!("{:?}", h.app.render_workspace.view.materials); ++ let mut expected = json!({"settings":{"exposure_ev":1.25}}); ++ cpu::params(&h.app, &mut expected).unwrap(); ++ let request = runtime_image_request(&h.app, false).unwrap(); ++ let mut options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); ++ options.validate().unwrap(); ++ assert_eq!(options.directional_shadow_transmission, shadows); ++ assert!(options.shadows); ++ assert_eq!(options.dielectrics.len(), 2); ++ assert_eq!(options.dielectric_transport, policy); ++ assert_eq!(options.progressive, h.app.render_workspace.view.raytrace.progressive); ++ assert!(options.dielectrics.iter().all(|body| body.ior == 1.5 && body.absorption_per_mm == [0.0; 3])); ++ assert!(request["raytrace"]["dielectrics"].as_array().unwrap().iter().all(|body| body.get("shadow_transmission").is_none())); ++ if !shadows { ++ assert!(request["raytrace"].get("directional_shadow_transmission").is_none()); ++ } ++ options.dielectrics.clear(); ++ options.directional_shadow_transmission = false; ++ assert_eq!(json!(options), expected["raytrace"], "no other CPU option may change"); ++ assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); ++ assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); ++ assert!(Arc::ptr_eq(&document, &h.app.session.doc)); ++ assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); ++ } ++ } ++ } ++ } ++ ++ #[test] ++ fn cpu_directional_shadow_mixed_body_choices_refuse_both_orders_without_erasing_off() { ++ for choices in [[false, true], [true, false]] { ++ let h = directional_shadow_fixture(&choices); ++ directional_shadow_refusal_is_atomic(&h, Some("render.cpu_shadow_mixed")); ++ } ++ } ++ ++ #[test] ++ fn cpu_directional_shadow_all_on_keeps_global_shadows_environment_nesting_and_light_refusals() { ++ for case in ["global_off", "constant", "hdr", "nested", "reflections", "punctual", "area"] { ++ let mut h = directional_shadow_fixture(&[true, true]); ++ match case { ++ "global_off" => h.app.render_workspace.view.raytrace.shadows = false, ++ "constant" => h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant, ++ "hdr" => { ++ h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; ++ h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-shadow-adapter.hdr"); ++ } ++ "nested" => h.app.render_workspace.view.cpu.nested_media = true, ++ "reflections" => h.app.render_workspace.view.raytrace.reflections = Some(Default::default()), ++ "punctual" => { ++ h.app.render_workspace.view.raytrace.punctual_lights = Some(serde_json::from_value(json!([{ ++ "position_mm":[0,0,100],"color":[1,1,1],"intensity":2,"reference_distance_mm":100,"minimum_distance_mm":0.01 ++ }])).unwrap()); ++ } ++ "area" => { ++ h.app.render_workspace.view.raytrace.area_lights = Some(serde_json::from_value(json!([{ ++ "center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3 ++ }])).unwrap()); ++ } ++ _ => unreachable!(), ++ } ++ h.app.render_workspace.view.raytrace.validate().unwrap(); ++ directional_shadow_refusal_is_atomic(&h, None); ++ } ++ } ++ ++ #[test] ++ fn cpu_directional_shadow_all_on_preserves_identity_permission_duplicate_and_boundary_gates() { ++ for case in ["stale", "duplicate", "closed", "permission"] { ++ let mut h = directional_shadow_fixture(&[true, true]); ++ match case { ++ "stale" => { ++ h.app.run("appearance.assign", json!({"bodies":["Shadow0"],"color":"#123456"})).unwrap(); ++ } ++ "duplicate" => { ++ let duplicate = h.app.render_workspace.view.materials.bindings[0].clone(); ++ h.app.render_workspace.view.materials.bindings.push(duplicate); ++ } ++ "closed" => h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Closed, ++ "permission" => h.app.render_workspace.view.materials.bindings[0].cpu_optics = false, ++ _ => unreachable!(), ++ } ++ directional_shadow_refusal_is_atomic(&h, None); ++ } ++ } ++ ++ #[test] ++ fn cpu_directional_shadow_inactive_off_body_is_not_selected_for_transmission() { ++ use solidcraft_engine::render::job::RaytraceOptions; ++ let mut h = directional_shadow_fixture(&[true, false]); ++ h.app.render_workspace.view.materials.bindings[1].enabled = false; ++ let request = runtime_image_request(&h.app, false).unwrap(); ++ let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); ++ assert!(options.directional_shadow_transmission); ++ assert_eq!(options.dielectrics.len(), 1); ++ assert_eq!(options.dielectrics[0].body_name, "Shadow0"); ++ assert!(!h.app.render_workspace.view.materials.bindings[1].glass.shadows); ++ assert!(!h.app.render_workspace.view.materials.bindings[1].enabled); ++ } ++ ++ #[test] ++ fn cpu_directional_shadow_default_false_and_conflicting_global_intent_are_preserved() { ++ use solidcraft_engine::render::job::RaytraceOptions; ++ assert!(!RaytraceOptions::default().directional_shadow_transmission); ++ assert!(json!(RaytraceOptions::default()).get("directional_shadow_transmission").is_none()); ++ let h = directional_shadow_fixture(&[false, false]); ++ let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"retain"}); ++ cpu::params(&h.app, &mut request).unwrap(); ++ request["raytrace"]["directional_shadow_transmission"] = json!(true); ++ let before = request.clone(); ++ assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_shadow_conflict"))); ++ assert_eq!(request, before); ++ assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); ++ let mut h = directional_shadow_fixture(&[true, false]); ++ h.app.render_workspace.view.materials.enabled = false; ++ let before = request.clone(); ++ materials::params(&h.app, &mut request).unwrap(); ++ assert_eq!(request, before, "disabled materials do not rewrite an unrelated request"); ++ } ++ ++ #[test] ++ fn cpu_directional_shadow_adapter_messages_are_delivered_in_nine_languages() { ++ for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { ++ let locale = crate::i18n::Locale::for_language(language); ++ for key in ["render.cpu_directional_shadow_help", "render.cpu_shadow_conflict", "render.cpu_shadow_mixed"] { ++ assert_ne!(locale.text(key), key, "{language}: {key}"); ++ assert!(!locale.text(key).is_empty(), "{language}: {key}"); ++ } ++ } ++ } ++ + #[test] + fn explicit_cpu_recipe_builds_typed_optics_with_independent_linear_units_and_no_design_edit() { + use solidcraft_engine::render::{ +--- a/crates/ui-egui/src/render_workspace_cpu.rs ++++ b/crates/ui-egui/src/render_workspace_cpu.rs +@@ -837,7 +837,16 @@ + assert_eq!(h.app.session.revision, revision); + super::interactive::apply_command(&mut h.app, Action::Off).unwrap(); + h.app.render_workspace.view.materials.bindings[0].glass.shadows = true; +- assert!(super::image_request(&h.app).is_err()); ++ let shadow_wire = super::image_request(&h.app).unwrap(); ++ let shadow_options: solidcraft_engine::render::job::RaytraceOptions = serde_json::from_value(shadow_wire["raytrace"].clone()).unwrap(); ++ assert!(shadow_options.directional_shadow_transmission); ++ assert!(shadow_options.shadows); ++ assert_eq!(shadow_options.dielectric_transport, h.app.render_workspace.view.raytrace.dielectric_transport); ++ assert_eq!(shadow_options.dielectrics[0].ior, 1.0); ++ let shadow_check = h.app.session.execute("render.preflight", &shadow_wire).unwrap(); ++ let shadow_request: solidcraft_engine::render::job::ImageRequest = serde_json::from_value(shadow_check["request"].clone()).unwrap(); ++ assert_eq!(shadow_request.raytrace.as_ref(), Some(&shadow_options)); ++ assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission, "the bridge is request-local"); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + h.app.render_workspace.view.materials.bindings[0].glass.shadows = false; + h.app.render_workspace.view.materials.bindings[0].maps_enabled = true; +--- /dev/null ++++ b/assets/locales/pending/cpu-directional-shadow-ui.json +@@ -0,0 +1,47 @@ ++{ ++ "en": { ++ "render.cpu_directional_shadow_help": "CPU optics are temporary and require certified sheets or axis-aligned boxes with opaque body and face appearances. Directional transmitted shadows require global shadows on and all active assignments to agree. Mixed choices, nesting, environment lighting and local lights are unsupported in that mode. This is straight RGB visibility, not refracted shadows or caustics. Subsurface, coats and maps remain unsupported; fixed and progressive sampling retain finite-depth limits.", ++ "render.cpu_shadow_conflict": "The global directional transmission option conflicts with an optical assignment whose transmitted shadows are off. No authored option was changed.", ++ "render.cpu_shadow_mixed": "CPU uses one transmitted-shadow switch for all active optical assignments. Mixed on/off choices cannot be represented and have been preserved." ++ }, ++ "es": { ++ "render.cpu_directional_shadow_help": "La óptica CPU es temporal y requiere láminas o cajas alineadas con los ejes certificadas, con aspectos opacos de cuerpo y caras. Las sombras transmitidas direccionales requieren sombras globales activadas y que todas las asignaciones activas coincidan. Ese modo no admite mezclas, nesting, iluminación de entorno ni luces locales. Es visibilidad RGB recta, sin sombras refractadas ni cáusticas. La dispersión subsuperficial, las capas y los mapas siguen sin admitirse; el muestreo fijo y progresivo conserva los límites de profundidad.", ++ "render.cpu_shadow_conflict": "La opción global de transmisión direccional contradice una asignación óptica con sombras transmitidas desactivadas. No se ha cambiado ninguna opción definida.", ++ "render.cpu_shadow_mixed": "CPU usa un único control de sombras transmitidas para todas las asignaciones ópticas activas. No puede representar opciones activadas y desactivadas mezcladas; se han conservado." ++ }, ++ "de": { ++ "render.cpu_directional_shadow_help": "CPU-Optik ist temporär und erfordert zertifizierte Scheiben oder achsenparallele Quader mit opaken Körper- und Flächenerscheinungen. Gerichtete durchgelassene Schatten erfordern globale Schatten und übereinstimmende aktive Zuweisungen. Gemischte Optionen, Verschachtelung, Umgebungslicht und lokale Lichter sind in diesem Modus nicht unterstützt. Dies ist geradlinige RGB-Sichtbarkeit, keine gebrochenen Schatten oder Kaustiken. Subsurface-Streuung, Beschichtungen und Maps bleiben nicht unterstützt; feste und progressive Abtastung behalten die endliche Tiefengrenze.", ++ "render.cpu_shadow_conflict": "Die globale gerichtete Transmission widerspricht einer optischen Zuweisung mit ausgeschalteten durchgelassenen Schatten. Keine festgelegte Option wurde geändert.", ++ "render.cpu_shadow_mixed": "CPU verwendet einen Schalter für durchgelassene Schatten aller aktiven optischen Zuweisungen. Gemischte Ein-/Aus-Werte sind nicht darstellbar und wurden beibehalten." ++ }, ++ "ko": { ++ "render.cpu_directional_shadow_help": "CPU 광학은 임시 설정이며 불투명한 바디와 면 외관을 가진 인증된 판 또는 축 정렬 상자가 필요합니다. 방향성 투과 그림자는 전역 그림자가 켜져 있고 모든 활성 할당의 설정이 같아야 합니다. 이 모드는 혼합 설정, 중첩, 환경 조명 및 로컬 광원을 지원하지 않습니다. 이는 직선 RGB 가시성이며 굴절 그림자나 코스틱이 아닙니다. 표면하 산란, 코팅 및 맵은 계속 지원하지 않으며 고정 및 점진적 샘플링은 유한 깊이 제한을 유지합니다.", ++ "render.cpu_shadow_conflict": "전역 방향성 투과 옵션이 투과 그림자가 꺼진 광학 할당과 충돌합니다. 작성된 옵션은 변경되지 않았습니다.", ++ "render.cpu_shadow_mixed": "CPU는 모든 활성 광학 할당에 하나의 투과 그림자 스위치를 사용합니다. 켜짐과 꺼짐이 섞인 설정은 표현할 수 없으며 그대로 보존되었습니다." ++ }, ++ "ar": { ++ "render.cpu_directional_shadow_help": "بصريات CPU مؤقتة وتتطلب صفائح أو صناديق محاذية للمحاور اجتازت التحقق، بمظاهر معتمة للجسم والأوجه. تتطلب الظلال النافذة الاتجاهية تفعيل الظلال العامة وتطابق كل التعيينات النشطة. لا يدعم هذا الوضع الخيارات المختلطة أو التداخل أو إضاءة البيئة أو الأضواء المحلية. هذه رؤية RGB مستقيمة وليست ظلالًا منكسرة أو كاوستيك. يبقى التشتت تحت السطحي والطلاءات والخرائط غير مدعوم، وتبقى حدود العمق المحدودة لأخذ العينات الثابت والتدريجي.", ++ "render.cpu_shadow_conflict": "يتعارض خيار النفاذ الاتجاهي العام مع تعيين بصري تكون ظلاله النافذة معطلة. لم يتغير أي خيار محدد.", ++ "render.cpu_shadow_mixed": "يستخدم CPU مفتاح ظلال نافذة واحدًا لجميع التعيينات البصرية النشطة. لا يمكن تمثيل خليط من التفعيل والتعطيل، وقد تم الاحتفاظ بالخيارات." ++ }, ++ "he": { ++ "render.cpu_directional_shadow_help": "אופטיקת CPU היא זמנית ודורשת יריעות או תיבות מיושרות לצירים שעברו אימות, עם מראה אטום של הגוף והפאות. צללים מועברים כיווניים דורשים צללים כלליים פעילים ואחידות בכל ההקצאות הפעילות. מצב זה אינו תומך בערכים מעורבים, קינון, תאורת סביבה או אורות מקומיים. זו נראות RGB בקו ישר, ללא צללים נשברים או קאוסטיקה. פיזור תת-משטחי, ציפויים ומפות עדיין אינם נתמכים; דגימה קבועה והדרגתית שומרות על מגבלות העומק הסופי.", ++ "render.cpu_shadow_conflict": "אפשרות ההעברה הכיוונית הכללית סותרת הקצאה אופטית שהצללים המועברים שלה כבויים. שום אפשרות שנקבעה לא שונתה.", ++ "render.cpu_shadow_mixed": "CPU משתמש במתג צללים מועברים אחד לכל ההקצאות האופטיות הפעילות. לא ניתן לייצג ערכים מעורבים של פעיל וכבוי, והם נשמרו." ++ }, ++ "ja": { ++ "render.cpu_directional_shadow_help": "CPU 光学設定は一時的で、不透明なボディと面の外観を持つ認証済みの薄板または軸に平行なボックスが必要です。平行光源の透過シャドウには全体のシャドウを有効にし、すべての有効な割り当ての設定を一致させる必要があります。このモードでは混在設定、入れ子、環境光、ローカルライトは非対応です。これは直線上の RGB 可視性であり、屈折シャドウやコースティクスではありません。表面下散乱、コート、マップは引き続き非対応で、固定およびプログレッシブサンプリングでも有限深度制限は残ります。", ++ "render.cpu_shadow_conflict": "全体の平行光透過オプションが、透過シャドウを無効にした光学割り当てと競合しています。設定したオプションは変更されていません。", ++ "render.cpu_shadow_mixed": "CPU はすべての有効な光学割り当てに単一の透過シャドウスイッチを使用します。有効と無効の混在は表現できないため、その設定を保持しています。" ++ }, ++ "vi": { ++ "render.cpu_directional_shadow_help": "Quang học CPU là tạm thời và cần tấm hoặc hộp song song các trục đã được kiểm chứng, với diện mạo thân và mặt đục. Bóng truyền qua từ đèn định hướng cần bật bóng toàn cục và mọi phép gán đang bật phải cùng lựa chọn. Chế độ này không hỗ trợ lựa chọn lẫn bật/tắt, lồng nhau, ánh sáng môi trường hoặc đèn cục bộ. Đây là độ nhìn thấy RGB theo đường thẳng, không phải bóng khúc xạ hay caustic. Tán xạ dưới bề mặt, lớp phủ và bản đồ vẫn không được hỗ trợ; lấy mẫu cố định và lũy tiến vẫn có giới hạn độ sâu hữu hạn.", ++ "render.cpu_shadow_conflict": "Tùy chọn truyền sáng định hướng toàn cục xung đột với phép gán quang học có bóng truyền qua đang tắt. Không thay đổi tùy chọn đã soạn nào.", ++ "render.cpu_shadow_mixed": "CPU dùng một công tắc bóng truyền qua cho tất cả phép gán quang học đang bật. Không thể biểu diễn lựa chọn lẫn bật và tắt; các lựa chọn đã được giữ nguyên." ++ }, ++ "zh": { ++ "render.cpu_directional_shadow_help": "CPU 光学设置是临时的,需要通过认证的薄片或轴对齐盒体,以及不透明的实体和面外观。方向光透射阴影要求开启全局阴影,并且所有启用的分配采用相同设置。此模式不支持混合开关、嵌套、环境照明或局部光源。这是直线 RGB 可见性,并非折射阴影或焦散。次表面散射、涂层和贴图仍不支持;固定和渐进采样仍保留有限深度限制。", ++ "render.cpu_shadow_conflict": "全局方向光透射选项与关闭透射阴影的光学分配冲突。未更改任何已设置的选项。", ++ "render.cpu_shadow_mixed": "CPU 对所有启用的光学分配使用一个透射阴影开关。无法表示开启和关闭混合的设置,已保留这些设置。" ++ } ++} diff --git a/proposals/render/2026-10-31/cpu-directional-shadow-ui/source-bindings.json b/proposals/render/2026-10-31/cpu-directional-shadow-ui/source-bindings.json new file mode 100644 index 000000000..a99311ba7 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-directional-shadow-ui/source-bindings.json @@ -0,0 +1,56 @@ +{ + "status": "SOURCE_ADOPTED_IN_C23_UNFORMATTED_UNCOMPILED_UNRUN", + "baseline_manifest_sha256": "9b193a92875783101d2511342eb4e4781abeb2f149187179f8900931fbd06e3f", + "C23_adopted_source_manifest_sha256": "55bcda795f1c124465330f9156ad6894501ac1e184203fe3e2994d1052eee45b", + "paths": [ + { + "path": "crates/ui-egui/src/render_workspace_materials.rs", + "before": { + "sha256": "22b2c1133789921d1d1d7eea0dbdc8b4662fd1fcce746143ccd30e200897d8b5", + "bytes": 54279 + }, + "candidate": { + "sha256": "9ae7a34a965878639e9f79a74c4983a93db9a0568019535984c97384d0f4cb13", + "bytes": 55277 + }, + "eol": "LF" + }, + { + "path": "crates/ui-egui/src/render_workspace_tests.rs", + "before": { + "sha256": "9aa14ddb50930aeb02b48e27bf146a0b53ab7d68139bac8971bf091756bbd6de", + "bytes": 607819 + }, + "candidate": { + "sha256": "39c50dd512df0741ed96f32be2e2095a3632776542679c10968a162560dacf69", + "bytes": 618884 + }, + "eol": "LF" + }, + { + "path": "crates/ui-egui/src/render_workspace_cpu.rs", + "before": { + "sha256": "4c144e8ee0c6a51380da60ecd70d350a66fce363261a6e711d24626df371be08", + "bytes": 41773 + }, + "candidate": { + "sha256": "3a06929c32104559374f62f4dd5134333c785345e4ba62762445f587a722daf9", + "bytes": 42638 + }, + "eol": "LF" + }, + { + "path": "assets/locales/pending/cpu-directional-shadow-ui.json", + "before": null, + "candidate": { + "sha256": "8f8cd93a753193ef93bdc3d1e7ffc16e4833065b3a73c5e23332339346745815", + "bytes": 9827 + }, + "eol": "LF" + } + ], + "new_tests_UNRUN": 7, + "old_main_test_bodies_preserved": 277, + "native_test_frontier_exception": "same original CPU fixture; old blanket shadow unsupported error replaced with typed-wire and real-preflight positive; no other oracle changed", + "scope": "uniform per-body ON/OFF only; mixed bodies refuse; no per-body mask or physical refraction/caustics claim" +}