docs(render): preserve reviewed parity preparation and original unrun acceptance cases
This commit is contained in:
1 parent
f6d3362ed2
commit
5de18a496e
9 files changed
+2292
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# Current-source cumulative V2 plus engine proposal
|
||||
|
||||
The current-rebind.patch is a single seven-path cumulative proposal against the pinned C12 receiver, replacing separate V2/engine applications; do not double-apply. It preserves current Area/LED, all213 UI declarations and all prior Render test prefixes. Only one NEW engine-test diagnostic literal is updated for the actual Area/LED contract; no historical assertion or optical oracle changes.
|
||||
|
||||
Independent numerical delta and Engine route reviews found no new actionable source blocker. It proposes13 Render and2 Engine declarations. All remain uncompiled/unrun and the proposal is NOT APPLIED. The shared C12 source remains frozen. Recheck exact preimages and dependencies before any later adoption. Existing V1 remains blocked and archived; general/progressive/Interactive glass and normal physical-library routing remain open.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
# Additional real CPU Interactive EV/HDR tests
|
||||
|
||||
Source-only, independently reviewed, NOT APPLIED/FORMATTED/COMPILED/RUN. Appends two original tests to the actual213-test C12 postformatter prefix, resulting in215 declarations. Do not apply both this patch and a whole test-file overlay.
|
||||
|
||||
EV0,+1,-1,0 follows real Snapshot/native CPU/admitted job/PNG/cache/upload. A normal-facing index-matched grey Lambert surface with one light has independently calculated display RGB51,72,35,51. Outer EV stays0; actual CPU job carries EV once. Reversal must restore identical PNG bytes. HDR adds accepted-image invalidation by pending intent, failed Resume, explicit Pause during real inspection/correction, actual CPU recovery and retention of that newly recovered frame when paused. Digest is checked on captured wire; no full job-HDR provenance, rotation/radiometry, desktop slider, Undo/Redo or in-place linear regrade claim is made.
|
||||
|
||||
Requires two positive real-CPU markers. A feature-disabled/refused branch is not qualification. Existing source remains frozen for C12, so these tests belong to a subsequent coherent validation batch, not its53-case selection.
|
||||
@@ -0,0 +1,184 @@
|
||||
diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs
|
||||
--- a/crates/ui-egui/src/render_workspace_tests.rs
|
||||
+++ b/crates/ui-egui/src/render_workspace_tests.rs
|
||||
@@ -8407,3 +8407,180 @@
|
||||
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();
|
||||
+}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Genuine midpass progress: private foundation
|
||||
|
||||
Selected direction: Option A from options.md, a bounded reduced snapshot of the actual accumulating final film. Option B is deferred. Neither host streaming nor UI integration is implemented.
|
||||
|
||||
A1 adds only separate read-only partial-film access and five original tests in the existing film test file. Actual source state yields counts s+(index<prefix). Unsampled pixels are explicitly Unknown; an observed miss has positive samples and zero coverage. Existing film layout, add/pixel methods, strict complete-pass consumer and original14-test byte prefix are unchanged. The five new declarations remain uncompiled/unrun.
|
||||
|
||||
This is an UNINTEGRATED SOURCE PROPOSAL, not a standalone gate candidate: new crate-internal types/methods currently have only test consumers, so dead_code under strict library Clippy is expected until the REAL A2 consumer is implemented. Do not add allow attributes, public visibility or dummy calls to disguise that dependency.
|
||||
|
||||
Required next seams include safe cursor-preserving resolve/resume, truthful partial/reduced metadata, bounded retained-image credits and backpressure on the existing lease, cumulative work, actual producer/receiver identity and export isolation. Current legacy power-of-two checkpoints still run unchanged. No long-scene latency/FPS, full glass, native acceptance or quality result is claimed.
|
||||
@@ -0,0 +1,104 @@
|
||||
# CPU visible progress inside a pass — two bounded options
|
||||
|
||||
Design/source inventory only. NO implementation, test body, numerical probe, build, app, shared mutation, Git or GitHub operation. Glass packets remain untouched. Source bindings are in source-bindings.json. Follow Engineer review before any code.
|
||||
|
||||
Recommendation: Option A as the smaller first increment, with a reduced bounded preview envelope; Option B only if direct tile updates/first-pixel responsiveness justify its additional commit and acknowledgement contract. Both require actual film-derived data. Neither raising preview_count nor reissuing the old texture is sufficient.
|
||||
|
||||
## Verified current seams
|
||||
|
||||
- film.rs29 maps film::primary to film_primary.rs. PrimaryFilm stores sum RGB and covered per pixel, global samples and next_pixel (film_primary.rs17). add validates scanline index/absolute ordinal, charges and checks cancel before the one mutation, then advances the prefix. pixel() at125 refuses a partial or empty pass.
|
||||
- raytrace/image.rs723 finish_sample commits film.add, clears PendingPixel and increments self.pixel. This is the safe completed-pixel snapshot seam. No partial ray/sample contribution may become a film sample.
|
||||
- image.rs878 camera jitter and secondary samplers use seed, logical final pixel and film.samples. No output sequence/timing enters keys; preserve that.
|
||||
- image.rs1449 resolves full request dimensions;1531 starts resolution only at final or power-of-two COMPLETE passes.1503 returns Preview then resets self.pixel=0. A midpass path must never execute that reset; it must save/restore the exact completed-pixel cursor.
|
||||
- host.rs WorkPoll/ImagePoll/PendingPng/PreviewInfo carry only one uniform samples_per_pixel;835 checks powers of two from sequence. RenderPreview contains PNG and a transferred Reservation; Reservation::split at113 is one-way and Drop releases to the global pool, not back to the running task.
|
||||
- image admission226 and CpuProgressiveOptions.preview_count mod.rs659 prepay every possible retained full PNG. This is valid for the finite existing sequence, not for a streaming sequence.
|
||||
- UI render_workspace_interactive.rs298 requires spp>=1 and preview dimensions equal request; general render_workspace.rs1325 also requires request-sized frames and labels uniform SPP. Both need explicit partial/reduced provenance, not weakened dimension checks.
|
||||
- Interactive Snapshot::run engine/render_interactive.rs228 already passes captured scene/request/options/environment to a distinct job; render/job/interactive.rs12 fits its request to1024. A final Workstation request can still be16384 on an edge and67,108,864 pixels. A preview envelope must not overwrite that final request/FrameInfo/export.
|
||||
|
||||
## Common invariants and proposed policy boundary
|
||||
|
||||
Keep PrimaryFilm.pixel strict for legacy complete-pass/final consumers. Add a separate proposed partial snapshot view; do not change old tests' partial-pass refusal. Existing default whole-pass checkpoint behavior and its exact PNG/work/sequence tests stay unchanged. An internal ephemeral presentation policy selecting the new behavior must be explicitly routed by Engineer through host construction/submission; there is no such policy API today. Do not infer it from JobId or add a saved/public request flag casually. If the behavior is intended for manual progressive jobs too, review that contract separately instead of silently changing the legacy observer.
|
||||
|
||||
A snapshot is captured only immediately after a successfully committed pixel with pending.is_none(). Keep the existing self.pixel, film.samples/next_pixel and every sampler ordinal unchanged. Resolving/encoding pauses integration over an immutable captured frontier; resume the SAME next pixel, never replay completed updates or discard a pending ray. At the full-pass boundary the existing cursor-N/film-next0 transition is special and remains distinct from a partial prefix.
|
||||
|
||||
For P final pixels, s completed passes and prefix k (0<=k<P):
|
||||
n(i)=s+1 when i<k, else s; c(i)=film's committed covered count; L(i)=sum(i)/n(i) only if n(i)>0.
|
||||
No new final-film sample counter is needed. A fresh descriptor records s,k,P and source dimensions, allowing counts for every source pixel. n=0 is UNSAMPLED, not a zero-radiance hit, opaque black, or a measured camera miss. n>0,c=0 is a real miss and retains the original display-sRGB backplate. c/n remains physical coverage; tone/exposure/composite occur once exactly as composite_spatial for sampled data.
|
||||
|
||||
New publications need a monotonic sequence independent of SPP, job+visual revision/generation, separate preview dimensions, captured frontier and sampling/reduction provenance. UI must show nonuniform counts/range/coverage honestly. A reduced snapshot cannot masquerade as final dimensions or a uniform1SPP frame. No export/final ownership transfer, old-generation adoption or reuse of a stale payload under a new sequence.
|
||||
|
||||
## Option A — bounded reduced whole-PNG snapshot of a partial final film
|
||||
|
||||
Smallest change to delivery: retain immutable independently decodable PNG checkpoints, but read a partial film into a bounded display grid, max edge1024 (existing Interactive ceiling), preserving final request and full film.
|
||||
|
||||
Use a deterministic PROPOSED representative-source mapping for each preview pixel (u,v):
|
||||
x=floor(u*W/w), y=floor(v*H/h), source_index=y*W+x.
|
||||
This is nearest representative sampling of committed final pixels, not a box average, new camera render, or full-resolution convergence statement. Top-left representatives allow the first committed source pixel to produce actual visible content. The mapping is fixed by captured dimensions and never affects trace pixel ids/seeds. A centered mapping is possible but delays first-row visibility; choose one explicitly before implementation.
|
||||
|
||||
Resolve at most M=w*h actual source pixels, not all P pixels. Each representative carries its actual n,c; n is derived from s,k and mapping, c requires a bounded u16 sidecar if exposed per preview pixel. The sidecar allocation is billed outside the fixed1024-byte FrameInfo metadata allowance. Unsampled cells use an explicit mask/transparent provisional presentation plus an unknown canvas treatment, never a fake sample/backplate claim.
|
||||
An unsampled visual placeholder is not the request's transparent_background setting and cannot become exportable output.
|
||||
|
||||
At a safe committed frontier with changed represented data and an available publication credit, pause and resolve O(M), encode at preview dimensions, hash incrementally, publish, then resume the exact final-film cursor. Reuse a bounded prefix of existing admitted RGBA scratch if safe; otherwise bill separate4M scratch. Do not allocate a second full final film or change camera rays. Coalesce dirty frontiers while publication is unavailable; do not encode an image the host cannot retain.
|
||||
|
||||
Pros: independent snapshots tolerate skipped frames; uses existing PNG decoder/upload path after explicit metadata changes; no tile acknowledgement/mosaic state. Keeps final accumulation byte order intact.
|
||||
Costs/limits: O(M) resolve, PNG encode, hash, decode and full preview upload for each new snapshot; representative aliasing; no fresh picture until geometry initialization and at least a useful committed pixel exist. It cannot guarantee a wall-time frame rate for a single expensive in-flight ray. Real cadence must be measured; no sleep/fake timer can establish it.
|
||||
|
||||
Required paths:
|
||||
film_primary.rs: new read-only partial accessor/frontier without relaxing pixel();
|
||||
raytrace/progressive.rs: snapshot/resume frontier;
|
||||
raytrace/image.rs: safe trigger, bounded resolve/encoder dimensions and cursor preservation, same work counter;
|
||||
job/host.rs + job/mod.rs: partial descriptor, sequence and resource-credit admission/publication;
|
||||
job/encoding.rs: existing dimensional encoder reused, not relabelled;
|
||||
engine/render_interactive.rs and its actual submission route: proposed ephemeral policy, captured revision;
|
||||
UI render_workspace_interactive.rs and render_workspace.rs: explicit source/preview dimensions, partial sample/unknown state; normal final decoder/export unchanged.
|
||||
Tests remain in film_tests.rs, primary_aa_tests.rs, host_tests.rs and existing engine/UI test files under their current owners.
|
||||
|
||||
## Option B — bounded reduced preview grid, dirty tile patches from committed samples
|
||||
|
||||
Retain the SAME final-film row-major loop. After each committed final pixel sample, update one cell in a separate bounded preview grid (max edge1024); cells correspond to integer source-pixel rectangles. This is preview-only state, not another renderer and not tile-first tracing.
|
||||
|
||||
Each display cell stores sum RGB, aggregate committed camera-attempt count N and aggregate primary-covered count C over its source footprint. L=sum/N is a weighted mean of committed attempts; C/N is its coverage. N=0 remains explicitly UNSAMPLED. N is not SPP: source pixels in a partially advanced footprint can have s or s+1 samples. The snapshot also records frontier s,k and footprint, so that source per-pixel counts remain derivable. Partial-footprint/weighted-preview provenance must be visible; no claim that it equals an equal-spatial-weight final downsample during an incomplete pass.
|
||||
|
||||
Update staging must be atomic with film.add: validate both new states and required work before either mutation, then commit without an intervening fallible/cancel boundary. Never commit film, fail preview work, and then replay the sample to repair the side grid. Each sum uses checked bounds; count type must cover the existing profile's total camera-sample cap, not u16 SPP.
|
||||
|
||||
Publish a bounded dirty rectangle/tile (e.g. a proposed32x32 cell cap) with exact rect, sequence/base, source frontier, actual N/C sidecar, encoding and job/revision identity. Copy/resolve O(T) committed display cells, not P; UI uploads that subrectangle to a bounded texture. Final film/request/PNG stay untouched. A raw tile is not a PNG or a final FrameInfo; use a distinct typed provisional payload, not a forged png_sha256.
|
||||
|
||||
Delivery MUST handle a slow UI: a delta may apply only to the exact acknowledged base/generation. Keep bounded dirty state and coalesce cells; require an explicit applied-sequence acknowledgement or a bounded full-grid resync if a delta was missed. One latest patch slot without ack/resync loses updates and is invalid. These APIs do not currently exist. No unbounded patch queue, history of tile images, or full-frame clone per patch.
|
||||
|
||||
Pros: new content can update a cell from each actual final-pixel commit; small resolve/upload latency and no repeated full PNG. Better fit when the first pass itself is slow.
|
||||
Costs: additional preview-grid sums/counts and charged work per commit, stricter dual-commit invariants, separate payload/UI texture-update path, acknowledgement/resync protocol and dirty-cell bookkeeping. This is broader than Option A; keep it confined to the same film/host/UI adapter rather than introduce a rendering framework.
|
||||
|
||||
Dependencies: all common paths above; replace PNG preview-only delivery with a typed raw-patch path in host/WorkPoll and UI, leave encoding.rs's final PNG logic untouched. film_primary.rs/add and image.rs/finish_sample require staged commit review; progressive.rs owns bounded grid/dirty state. No BVH, BSDF, sampler, kernel or saved-format change.
|
||||
|
||||
## Cost at the actual large envelopes
|
||||
|
||||
Current limits are numerical admission bounds, not qualified performance results:
|
||||
Workstation max edge16384 / max pixels67,108,864; max job12GiB. Primary Pixel layout is target-dependent, commonly32bytes (verify target), so this film alone is about2GiB; final RGBA256MiB.
|
||||
Current encoded bound image.rs229 is8P+65,536: at67,108,864 it is512MiB+64KiB for EACH full-size PNG capacity, before metadata. A complete snapshot also resolves67million pixels and scans/encodes/hashes proportional to that size. Repeating this midpass is not a bounded low-latency display solution.
|
||||
|
||||
Both options bound DISPLAY pixels M<=1,048,576 independently. Option A encoded capacity <=8MiB+64KiB plus up to2MiB covered-count sidecar and4MiB working RGBA (or already paid scratch). A16384x4096 final would display at1024x256, not secretly render/export at that resolution. No O(P) downsample scan is hidden: A reads representative indices only.
|
||||
Option B's grid with3f64 sums+2u64 counts is nominal40M bytes plus checked actual layout/dirty state, at most about40MiB for M=1,048,576. A32x32 patch is at most1024 display cells; include RGBA, N/C arrays, headers and staging in the same admission. These are estimates to verify in source/target, not benchmarked gains.
|
||||
|
||||
## Retained copies and backpressure: necessary for BOTH options
|
||||
|
||||
Proposed fixed K=2 independently retainable preview allocations plus ONE bounded in-flight encode/copy slot, all paid by the existing job/host lease and existing profile ceiling. K is a review choice, not a new public budget. Cloned Arcs of one payload do not count as another PNG allocation.
|
||||
Admission must use this peak and actual allocated capacities, not preview_count times all future frames. Do not lower admission thresholds or pretend immutable external payloads disappeared.
|
||||
Reservation::split alone cannot recycle publication capacity: last-drop releases globally, while the task's original reservation remains depleted. A small per-job lease-credit return/merge seam on the SAME Budget identity is needed; it is not currently implemented. No mutable buffer is reused while an external Arc exists. On terminal cleanup free credits release, externally held payloads retain their actual lease until last-drop; final PNG owns its independent unchanged lease.
|
||||
If K payloads remain externally held, do not resolve/encode/copy another checkpoint. Continue tracing, coalesce dirty progress and publish the newest actual data when a credit returns. Never block final completion waiting for an uncooperative consumer. Show the last payload as older data with its original provenance, not as a freshly rendered texture.
|
||||
|
||||
All initialization/read/copy/resolve/encode/hash work and cancellation use the SAME existing cumulative WorkBudget. No new work budget, reset, uncharged scan, off-thread helper renderer or side pool. Extra snapshots have real cost: cannot honestly promise the same historical total used units or unconditional completion at an already exhausted cap. A reviewed deterministic production trigger (independent of worker quantum/seed) and finite presentation-work scheduling/coalescing are required. Backpressure changes presentation work, never sample ordinals. If the requirement were identical historical work consumption, arbitrary additional presentations are impossible unless replacing existing presentation work; raise this explicitly rather than hide cost.
|
||||
Legacy mode keeps its old work/quantum/power-of-two tests unchanged. New-policy tests must separate invariant trace results from honestly charged optional presentation work and require LimitExceeded before partial mutation/publication. No invented wall-clock cadence acceptance; later native measurements include resolve/encode/hash/decode/upload.
|
||||
|
||||
## Original oracles to propose, not execute
|
||||
|
||||
1. Four-pixel raw-film frontier: after first two commits, s0/k2 -> n[1,1,0,0], c[1,0,0,0]; pixel0 radiance[2,0,0], pixel1 real miss, pixels2/3 explicitly UNSAMPLED. After one pass plus two commits, n[2,2,1,1]. With p0 first[2,0,0], second[4,0,0], its mean is[3,0,0], covered2. With p1 firstmiss, second[0,2,0], its premultiplied mean is[0,1,0], covered1/2. No division by zero or black-unobserved fiction.
|
||||
2. Snapshot/resume at k=1 and k=P-1 and full-pass sentinel: exact next (pixel,ordinal) sequence equals no-partial-preview control, including non-power-of-two target5, seeds0/123, Area1/4/16/64 and HDR/reflection existing fixtures. Compare final PNG bytes and film sum f64 bits, not just visual tolerance. No call-size/timing key enters variates.
|
||||
3. Existing camera_film_keeps_linear_sums_coverage_and_uniform_absolute_passes still rejects legacy pixel() during a partial pass. New accessor accepts exactly the observed frontier, not arbitrary/trusted input counters.
|
||||
4. Sampling/coverage display: N>0,C0 preserves exact backplate regardless exposure; unknownN0 is separately flagged. Mixed coverage computes physical C/N and tones once, never averages encoded RGB. A representative mapping must match its chosen source index. B aggregate box of4 committed attempts [2,0,0],miss,[0,2,0],miss yields sum[2,2,0],N4,C2,premultiplied mean[.5,.5,0],coverage.5.
|
||||
5. K=2 held external payloads: third publication performs zero new buffer allocation/encode, no new sequence; tracing continues. Release one -> next published payload carries the LATEST real frontier, not queued old progress. Cancel/replace during resolve/hash/publication cannot attach a late preview; old external immutable payload stays billed. Final completes while credits are full, independent final-frame lease. Check actual capacities/pool return and last-drop behavior.
|
||||
6. B only: apply exact base then patch yields known mosaic; missing/duplicate/out-of-order/generation-mismatched patch refuses or performs bounded explicit resync. N/C and dirty-cell versions cannot be silently lost by replacing a latest slot.
|
||||
7. Resource/cadence acceptance: a high-size request keeps final16384x4096 while preview<=1024edge; instrument bounded read/copy/encoder/upload counts to show no hidden P scan in A/B previews. A deterministic safe-pixel barrier can show a new payload before pass completion without sleeps; this proves midpass publication, not FPS. Later native timed evidence is separate and must include actual preparation and worst pixel stalls.
|
||||
|
||||
## Decision requested from Engineer, not user permission
|
||||
|
||||
Select A or B, confirm transient routing/default compatibility, preview-side count/provenance fields and the K-credit lifecycle, and define the new-mode presentation work/trigger contract. Then assign disjoint film/host/UI ownership with existing Area/LED/glass preserved. No implementation is authorized by this report. No timer, deadline, app control or automatic successor was created.
|
||||
@@ -0,0 +1,246 @@
|
||||
--- a/crates/render/src/film_primary.rs
|
||||
+++ b/crates/render/src/film_primary.rs
|
||||
@@ -10,6 +10,23 @@
|
||||
struct Pixel {
|
||||
sum: [f64; 3],
|
||||
covered: u32,
|
||||
+}
|
||||
+
|
||||
+/// Observed scanline frontier; metadata only, never a caller-supplied authority.
|
||||
+/// Every pixel before updated_prefix has one more sample than completed_passes.
|
||||
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
+pub(crate) struct PartialFrontier {
|
||||
+ pub completed_passes: u32,
|
||||
+ pub updated_prefix: usize,
|
||||
+ pub pixels: usize,
|
||||
+}
|
||||
+
|
||||
+/// A partial view never invents a zero sample for a pixel not yet observed.
|
||||
+/// Sampled linear radiance includes zero contributions from primary misses.
|
||||
+#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
+pub(crate) enum PartialPixel {
|
||||
+ Unknown,
|
||||
+ Sampled { linear_premultiplied: [f64; 3], covered: u32, count: u32 },
|
||||
}
|
||||
|
||||
pub(crate) struct PrimaryFilm {
|
||||
@@ -121,4 +138,49 @@
|
||||
let samples = u16::try_from(self.samples).map_err(|_| limit("primary sample count exceeds resolve representation"))?;
|
||||
Ok((pixel.sum.map(|sum| sum / f64::from(self.samples)), covered, samples))
|
||||
}
|
||||
+ /// Inspect only the real committed state. This value does not freeze the film
|
||||
+ /// or authorize a snapshot. A caller resolving several pixels must keep the
|
||||
+ /// film immutably borrowed at one completed-pixel frontier, and must charge
|
||||
+ /// reads/copies and check cancellation against its existing job budget.
|
||||
+ pub(crate) fn partial_frontier(&self) -> Result<PartialFrontier> {
|
||||
+ if !self.ready()
|
||||
+ || self.next_pixel >= self.count
|
||||
+ || self.samples > self.sample_limit
|
||||
+ || (self.samples == self.sample_limit && self.next_pixel != 0)
|
||||
+ {
|
||||
+ return Err(invalid("primary film has no initialized partial frontier"));
|
||||
+ }
|
||||
+ Ok(PartialFrontier { completed_passes: self.samples, updated_prefix: self.next_pixel, pixels: self.count })
|
||||
+ }
|
||||
+
|
||||
+ /// Bounded allocation-free read, separate from the strict complete-pass pixel().
|
||||
+ /// Counts come from this film, never from a supplied frontier or sample count.
|
||||
+ /// Unknown means count0/covered0; a sampled miss has count>0 and covered0.
|
||||
+ /// No exposure, tone mapping, background, work lease or publication occurs here.
|
||||
+ /// The caller owes cancellation checks and work charges for each read/copy;
|
||||
+ /// this accessor creates no independent budget and never advances an ordinal.
|
||||
+ pub(crate) fn partial_pixel(&self, index: usize) -> Result<PartialPixel> {
|
||||
+ let frontier = self.partial_frontier()?;
|
||||
+ let pixel = self.pixels.get(index).ok_or_else(|| invalid("primary film partial index out of range"))?;
|
||||
+ let count = frontier
|
||||
+ .completed_passes
|
||||
+ .checked_add(u32::from(index < frontier.updated_prefix))
|
||||
+ .filter(|count| *count <= self.sample_limit)
|
||||
+ .ok_or_else(|| limit("primary partial sample count exceeded"))?;
|
||||
+ if pixel.covered > count {
|
||||
+ return Err(invalid("primary partial coverage exceeds its committed count"));
|
||||
+ }
|
||||
+ if count == 0 {
|
||||
+ if pixel.covered != 0 || pixel.sum != [0.0; 3] {
|
||||
+ return Err(invalid("unobserved primary pixel has accumulated data"));
|
||||
+ }
|
||||
+ return Ok(PartialPixel::Unknown);
|
||||
+ }
|
||||
+ Ok(PartialPixel::Sampled {
|
||||
+ linear_premultiplied: pixel.sum.map(|sum| sum / f64::from(count)),
|
||||
+ covered: pixel.covered,
|
||||
+ count,
|
||||
+ })
|
||||
+ }
|
||||
+
|
||||
}
|
||||
--- a/crates/render/src/film_tests.rs
|
||||
+++ b/crates/render/src/film_tests.rs
|
||||
@@ -275,3 +275,167 @@
|
||||
assert!(film.add(0, 512, [0.0; 3], true, &cancel, &mut || Ok(())).is_err());
|
||||
assert_eq!(film.samples(), 512);
|
||||
}
|
||||
+
|
||||
+
|
||||
+#[cfg(feature = "raytrace-cpu")]
|
||||
+mod partial_camera_passes {
|
||||
+ use super::primary::{PartialFrontier, PartialPixel, PrimaryFilm};
|
||||
+ use super::*;
|
||||
+ use crate::job::{CpuBudget, CpuProgressiveOptions};
|
||||
+
|
||||
+ fn uninitialized(samples: u32, seed: u32) -> PrimaryFilm {
|
||||
+ let options = CpuProgressiveOptions { samples_per_pixel: samples, seed };
|
||||
+ let bytes = PrimaryFilm::required_bytes(4, 1, options, CpuBudget::Compact).unwrap();
|
||||
+ PrimaryFilm::new(4, 1, options, bytes, &CancelToken::default(), CpuBudget::Compact).unwrap()
|
||||
+ }
|
||||
+
|
||||
+ fn ready(samples: u32, seed: u32) -> PrimaryFilm {
|
||||
+ let mut film = uninitialized(samples, seed);
|
||||
+ while !film.ready() {
|
||||
+ film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap();
|
||||
+ }
|
||||
+ film
|
||||
+ }
|
||||
+
|
||||
+ fn observe(film: &PrimaryFilm) -> (PartialFrontier, Vec<PartialPixel>) {
|
||||
+ (film.partial_frontier().unwrap(), (0..4).map(|index| film.partial_pixel(index).unwrap()).collect())
|
||||
+ }
|
||||
+
|
||||
+ fn sampled(mean: [f64; 3], covered: u32, count: u32) -> PartialPixel {
|
||||
+ PartialPixel::Sampled { linear_premultiplied: mean, covered, count }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn partial_frontier_distinguishes_first_prefix_miss_and_unobserved_pixels() {
|
||||
+ let mut film = ready(2, 7);
|
||||
+ assert_eq!(observe(&film), (
|
||||
+ PartialFrontier { completed_passes: 0, updated_prefix: 0, pixels: 4 },
|
||||
+ vec![PartialPixel::Unknown; 4],
|
||||
+ ));
|
||||
+ film.add(0, 0, [2.0, 0.0, 0.0], true, &CancelToken::default(), &mut || Ok(())).unwrap();
|
||||
+ film.add(1, 0, [0.0; 3], false, &CancelToken::default(), &mut || Ok(())).unwrap();
|
||||
+ assert_eq!(observe(&film), (
|
||||
+ PartialFrontier { completed_passes: 0, updated_prefix: 2, pixels: 4 },
|
||||
+ vec![sampled([2.0, 0.0, 0.0], 1, 1), sampled([0.0; 3], 0, 1), PartialPixel::Unknown, PartialPixel::Unknown],
|
||||
+ ));
|
||||
+ assert!(film.pixel(0).is_err(), "legacy whole-pass reader still rejects the partial pass");
|
||||
+ assert!(film.pixel(1).is_err(), "a sampled miss does not imply a uniform pass");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn partial_counts_and_means_follow_real_interior_and_full_pass_frontiers() {
|
||||
+ let mut film = ready(2, 0);
|
||||
+ let cancel = CancelToken::default();
|
||||
+ for (index, value, covered) in [
|
||||
+ (0, [2.0, 0.0, 0.0], true), (1, [0.0; 3], false),
|
||||
+ (2, [0.0, 0.0, 4.0], true), (3, [0.0; 3], false),
|
||||
+ ] {
|
||||
+ film.add(index, 0, value, covered, &cancel, &mut || Ok(())).unwrap();
|
||||
+ }
|
||||
+ assert_eq!(film.partial_frontier().unwrap(), PartialFrontier { completed_passes: 1, updated_prefix: 0, pixels: 4 });
|
||||
+ assert_eq!(film.partial_pixel(3).unwrap(), sampled([0.0; 3], 0, 1));
|
||||
+ assert_eq!(film.pixel(0).unwrap(), ([2.0, 0.0, 0.0], 1, 1));
|
||||
+
|
||||
+ film.add(0, 1, [4.0, 0.0, 0.0], true, &cancel, &mut || Ok(())).unwrap();
|
||||
+ film.add(1, 1, [0.0, 2.0, 0.0], true, &cancel, &mut || Ok(())).unwrap();
|
||||
+ assert_eq!(observe(&film), (
|
||||
+ PartialFrontier { completed_passes: 1, updated_prefix: 2, pixels: 4 },
|
||||
+ vec![sampled([3.0, 0.0, 0.0], 2, 2), sampled([0.0, 1.0, 0.0], 1, 2),
|
||||
+ sampled([0.0, 0.0, 4.0], 1, 1), sampled([0.0; 3], 0, 1)],
|
||||
+ ));
|
||||
+ assert!(film.pixel(0).is_err());
|
||||
+
|
||||
+ film.add(2, 1, [0.0, 0.0, 8.0], true, &cancel, &mut || Ok(())).unwrap();
|
||||
+ assert_eq!(film.partial_frontier().unwrap().updated_prefix, 3);
|
||||
+ film.add(3, 1, [0.0; 3], false, &cancel, &mut || Ok(())).unwrap();
|
||||
+ assert_eq!(observe(&film), (
|
||||
+ PartialFrontier { completed_passes: 2, updated_prefix: 0, pixels: 4 },
|
||||
+ vec![sampled([3.0, 0.0, 0.0], 2, 2), sampled([0.0, 1.0, 0.0], 1, 2),
|
||||
+ sampled([0.0, 0.0, 6.0], 2, 2), sampled([0.0; 3], 0, 2)],
|
||||
+ ));
|
||||
+ assert_eq!(film.pixel(2).unwrap(), ([0.0, 0.0, 6.0], 2, 2));
|
||||
+ assert!(film.add(0, 2, [0.0; 3], false, &cancel, &mut || Ok(())).is_err());
|
||||
+ assert_eq!(film.partial_frontier().unwrap().completed_passes, 2);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn partial_access_refuses_uninitialized_storage_and_invalid_indices() {
|
||||
+ let mut film = uninitialized(2, 7);
|
||||
+ assert!(film.partial_frontier().is_err());
|
||||
+ assert!(film.partial_pixel(0).is_err());
|
||||
+ film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap();
|
||||
+ assert!(film.partial_frontier().is_err(), "allocated prefix is not an initialized film");
|
||||
+ assert!(film.partial_pixel(0).is_err());
|
||||
+ while !film.ready() {
|
||||
+ film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap();
|
||||
+ }
|
||||
+ assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Unknown);
|
||||
+ assert!(film.partial_pixel(4).is_err());
|
||||
+ assert!(film.partial_pixel(usize::MAX).is_err());
|
||||
+ assert_eq!(film.partial_frontier().unwrap().updated_prefix, 0);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn failed_or_cancelled_updates_preserve_the_observed_partial_frontier() {
|
||||
+ let mut film = ready(2, 7);
|
||||
+ film.add(0, 0, [2.0, 0.0, 0.0], true, &CancelToken::default(), &mut || Ok(())).unwrap();
|
||||
+ let before = observe(&film);
|
||||
+ for (index, ordinal, value, covered) in [
|
||||
+ (0, 0, [0.0; 3], false), (2, 0, [0.0; 3], false), (1, 1, [0.0; 3], false),
|
||||
+ (1, 0, [f64::NAN; 3], true), (1, 0, [1.0; 3], false),
|
||||
+ ] {
|
||||
+ assert!(film.add(index, ordinal, value, covered, &CancelToken::default(), &mut || Ok(())).is_err());
|
||||
+ assert_eq!(observe(&film), before);
|
||||
+ }
|
||||
+ assert_eq!(film.add(1, 0, [4.0; 3], true, &CancelToken::default(), &mut || Err(limit("existing job exhausted"))).unwrap_err().code,
|
||||
+ ErrorCode::LimitExceeded);
|
||||
+ assert_eq!(observe(&film), before);
|
||||
+ let cancel = CancelToken::default();
|
||||
+ let observer = cancel.clone();
|
||||
+ assert_eq!(film.add(1, 0, [4.0; 3], true, &cancel, &mut || {
|
||||
+ observer.cancel();
|
||||
+ Ok(())
|
||||
+ }).unwrap_err().code, ErrorCode::Cancelled);
|
||||
+ assert_eq!(observe(&film), before);
|
||||
+ film.add(1, 0, [4.0; 3], true, &CancelToken::default(), &mut || Ok(())).unwrap();
|
||||
+ assert_eq!(film.partial_frontier().unwrap().updated_prefix, 2, "failed updates did not consume the next ordinal");
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn reading_partial_pixels_preserves_default_sum_order_bits_and_charge_count() {
|
||||
+ for seed in [0, 7, u32::MAX] {
|
||||
+ let mut observed = ready(4, seed);
|
||||
+ let mut control = ready(4, seed);
|
||||
+ let mut observed_charges = 0;
|
||||
+ let mut control_charges = 0;
|
||||
+ for ordinal in 0..4 {
|
||||
+ let red = if ordinal == 0 { 1e12 } else { 2.0_f64.powi(-15) };
|
||||
+ for index in 0..4 {
|
||||
+ let value = [red, red * 0.5, 2.0];
|
||||
+ observed.add(index, ordinal, value, true, &CancelToken::default(), &mut || {
|
||||
+ observed_charges += 1;
|
||||
+ Ok(())
|
||||
+ }).unwrap();
|
||||
+ // These uncharged O(1) reads model only the accessor. A future
|
||||
+ // snapshot caller still owes its own per-read/copy work charge.
|
||||
+ let _ = observe(&observed);
|
||||
+ control.add(index, ordinal, value, true, &CancelToken::default(), &mut || {
|
||||
+ control_charges += 1;
|
||||
+ Ok(())
|
||||
+ }).unwrap();
|
||||
+ }
|
||||
+ }
|
||||
+ assert_eq!((observed_charges, control_charges), (16, 16));
|
||||
+ assert_eq!(observed.samples(), 4);
|
||||
+ for index in 0..4 {
|
||||
+ let (actual, covered, count) = observed.pixel(index).unwrap();
|
||||
+ let (expected, expected_covered, expected_count) = control.pixel(index).unwrap();
|
||||
+ assert_eq!(actual.map(f64::to_bits), expected.map(f64::to_bits));
|
||||
+ assert_eq!(actual.map(f64::to_bits), [2.5e11_f64, 1.25e11_f64, 2.0_f64].map(f64::to_bits),
|
||||
+ "ordered additions keep each sub-half-ULP contribution rounded at its original addition");
|
||||
+ assert_eq!((covered, count), (expected_covered, expected_count));
|
||||
+ assert_eq!(observed.partial_pixel(index).unwrap(), sampled(actual, 4, 4));
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Explicit internal output limits: seven-helper preparation
|
||||
|
||||
Source-only reviewed V2, NOT APPLIED/FORMATTED/COMPILED/RUN. Seven existing helpers share explicitly bounded internal RenderLimits policies for presentation, bloom, photographic effects, EXR encoding/decoding, PNG and regrade. Public GPU wrappers retain their current limits and supported-image behavior. The policy is not a host reservation or a CPU capability. No CPU host caller, raw transport, WorkBudget charging, EXR producer metadata or feature enablement is implemented here.
|
||||
|
||||
Thirteen original proposed tests preserve the nine previous declarations. They include independent linear radiance/coverage and bloom-kernel oracles, narrow8193x1 threading, exact-fit and hostile-policy refusal, default bytes and cancellation/validation ordering. The first source review identified changed legacy PNG cancellation precedence before new retained-capacity checks. V2 restores the original immediate cancel check after the original dimension/length checks; the other six candidates and all tests remain byte-identical. Independent delta review found no new source blocker. No image, compiler, Clippy or runtime result is claimed.
|
||||
|
||||
CPU enablement still requires captured raw scene-linear samples, correct acquired peak-buffer leases and cumulative work, coherent per-request output limits, publication/cancellation and real end-to-end tests. Passing a caller-created policy alone never acquires memory. The implementation rejects policies beyond existing Workstation maxima without raising those maxima. Do not mix this preparatory patch with an unrelated host overlay.
|
||||
@@ -0,0 +1,709 @@
|
||||
--- a/crates/render/src/job/presentation.rs
|
||||
+++ b/crates/render/src/job/presentation.rs
|
||||
@@ -45,6 +45,11 @@
|
||||
pub fn display(self, width: u32, height: u32) -> Result<Display> {
|
||||
self.validate()?;
|
||||
super::linear_exr::encoded_limit(width, height)?;
|
||||
+ self.display_with_limits(width, height, super::GPU_PATH_LIMITS)
|
||||
+ }
|
||||
+ pub(crate) fn display_with_limits(self, width: u32, height: u32, limits: crate::RenderLimits) -> Result<Display> {
|
||||
+ self.validate()?;
|
||||
+ super::linear_exr::output_pixels_with_limits(width, height, limits)?;
|
||||
Ok(Display {
|
||||
width,
|
||||
height,
|
||||
@@ -97,6 +102,19 @@
|
||||
return Err(JobError::new(ErrorCode::InvalidRequest, "bloom/display length mismatch"));
|
||||
}
|
||||
super::linear_exr::encoded_limit(self.width, self.height)?;
|
||||
+ self.encode_bloom_at_with_limits(input, output, cancel, offset, bloom, super::GPU_PATH_LIMITS)
|
||||
+ }
|
||||
+ pub(crate) fn encode_bloom_at_with_limits(
|
||||
+ self, input: &[[f32; 4]], output: &mut [u8], cancel: &CancelToken,
|
||||
+ offset: usize, bloom: Option<&[[f32; 3]]>, limits: crate::RenderLimits,
|
||||
+ ) -> Result<()> {
|
||||
+ if bloom.is_some_and(|pixels| pixels.len() != input.len()) {
|
||||
+ return Err(JobError::new(ErrorCode::InvalidRequest, "bloom/display length mismatch"));
|
||||
+ }
|
||||
+ let count = super::linear_exr::output_pixels_with_limits(self.width, self.height, limits)?;
|
||||
+ super::linear_exr::checked_output_bytes(count, 16, 0, limits)?;
|
||||
+ super::linear_exr::checked_output_bytes(count, 4, 0, limits)?;
|
||||
+ if bloom.is_some() { super::linear_exr::checked_output_bytes(count, 12, 0, limits)?; }
|
||||
self.finishing.validate()?;
|
||||
if let Some(backdrop) = self.backdrop {
|
||||
backdrop.validate()?;
|
||||
@@ -143,3 +161,49 @@
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::*;
|
||||
+
|
||||
+ #[test]
|
||||
+ fn raw_radiance_ev_and_coverage_have_independent_analytic_display_oracles() {
|
||||
+ let raw = [[4.0, 1.0, 0.25, 1.0], [2.0, 0.5, 0.125, 0.5]];
|
||||
+ let before = raw.map(|pixel| pixel.map(f32::to_bits));
|
||||
+ let display = Presentation { exposure_ev: 1.0, background: [0; 3], ..Default::default() }.display(2, 1).unwrap();
|
||||
+ let mut output = [0; 8];
|
||||
+ display.encode(&raw, &mut output, &CancelToken::default()).unwrap();
|
||||
+ let opaque = [8.0 / 9.0, 2.0 / 3.0, 1.0 / 3.0].map(solidcraft_geom::srgb::encode8);
|
||||
+ let covered = [4.0 / 9.0, 1.0 / 3.0, 1.0 / 6.0].map(solidcraft_geom::srgb::encode8);
|
||||
+ assert_eq!(&output[..4], &[opaque[0], opaque[1], opaque[2], 255]);
|
||||
+ assert_eq!(&output[4..], &[covered[0], covered[1], covered[2], 255]);
|
||||
+ assert_eq!(raw.map(|pixel| pixel.map(f32::to_bits)), before);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn wide_display_requires_explicit_policy_on_both_calls_without_allocating_a_frame() {
|
||||
+ let wide = super::super::CpuBudget::Workstation.image_limits(false);
|
||||
+ assert!(Presentation::default().display(8193, 1).is_err());
|
||||
+ let display = Presentation::default().display_with_limits(8193, 1, wide).unwrap();
|
||||
+ let mut output = [0; 4];
|
||||
+ let raw = [[1.0, 0.0, 0.0, 1.0]];
|
||||
+ assert!(display.encode_at(&raw, &mut output, &CancelToken::default(), 8192).is_err());
|
||||
+ display.encode_bloom_at_with_limits(&raw, &mut output, &CancelToken::default(), 8192, None, wide).unwrap();
|
||||
+ assert_eq!(output, [solidcraft_geom::srgb::encode8(0.5), 0, 0, 255]);
|
||||
+ assert!(display.encode_bloom_at_with_limits(&raw, &mut output, &CancelToken::default(), 8193, None, wide).is_err());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn explicit_gpu_display_matches_legacy_and_preserves_validation_before_cancel() {
|
||||
+ let display = Presentation { exposure_ev: -1.0, ..Default::default() }.display(3, 2).unwrap();
|
||||
+ let input = [[0.125, 2.0, 0.5, 1.0]; 6];
|
||||
+ let mut legacy = [0; 24];
|
||||
+ let mut explicit = [0; 24];
|
||||
+ display.encode(&input, &mut legacy, &CancelToken::default()).unwrap();
|
||||
+ display.encode_bloom_at_with_limits(&input, &mut explicit, &CancelToken::default(), 0, None, super::super::GPU_PATH_LIMITS).unwrap();
|
||||
+ assert_eq!(explicit, legacy);
|
||||
+ let cancel = CancelToken::default(); cancel.cancel();
|
||||
+ assert_eq!(display.encode(&[], &mut explicit, &cancel).unwrap_err().code, ErrorCode::InvalidRequest);
|
||||
+ assert_eq!(display.encode(&input, &mut explicit, &cancel).unwrap_err().code, ErrorCode::Cancelled);
|
||||
+ }
|
||||
+}
|
||||
--- a/crates/render/src/job/bloom.rs
|
||||
+++ b/crates/render/src/job/bloom.rs
|
||||
@@ -39,6 +39,13 @@
|
||||
return Ok(0);
|
||||
}
|
||||
u64::from(width).checked_mul(u64::from(height)).and_then(|n| n.checked_mul(24)).ok_or_else(|| invalid("bloom scratch overflow"))
|
||||
+ }
|
||||
+ pub(crate) fn scratch_bytes_with_limits(self, width: u32, height: u32, limits: crate::RenderLimits) -> Result<u64> {
|
||||
+ self.validate()?;
|
||||
+ let count = super::linear_exr::output_pixels_with_limits(width, height, limits)?;
|
||||
+ if !self.active() { return Ok(0); }
|
||||
+ super::linear_exr::checked_output_bytes(count, 12, 0, limits)?;
|
||||
+ super::linear_exr::checked_stage_bytes(count, 24, 0, limits)
|
||||
}
|
||||
}
|
||||
fn invalid(message: &str) -> JobError {
|
||||
@@ -64,21 +71,30 @@
|
||||
}
|
||||
impl BloomTask {
|
||||
pub fn new(width: u32, height: u32, pixels: Vec<[f32; 4]>, options: Bloom, cancel: CancelToken) -> Result<Self> {
|
||||
+ Self::new_with_limits(width, height, pixels, options, cancel, GPU_PATH_LIMITS)
|
||||
+ }
|
||||
+ pub(crate) fn new_with_limits(width: u32, height: u32, pixels: Vec<[f32; 4]>, options: Bloom, cancel: CancelToken, limits: crate::RenderLimits) -> Result<Self> {
|
||||
options.validate()?;
|
||||
cancel.check()?;
|
||||
let count = u64::from(width).checked_mul(u64::from(height)).ok_or_else(|| invalid("bloom dimensions overflow"))?;
|
||||
if width == 0
|
||||
|| height == 0
|
||||
- || u64::from(width) > GPU_PATH_LIMITS.max_dimension
|
||||
- || u64::from(height) > GPU_PATH_LIMITS.max_dimension
|
||||
- || count > GPU_PATH_LIMITS.max_pixels
|
||||
+ || super::linear_exr::output_pixels_with_limits(width, height, limits).is_err()
|
||||
|| usize::try_from(count).ok() != Some(pixels.len())
|
||||
|| !options.active()
|
||||
{
|
||||
return Err(invalid("bloom requires an admitted nonempty image and positive strength"));
|
||||
}
|
||||
+ options.scratch_bytes_with_limits(width, height, limits)?;
|
||||
+ let retained = super::linear_exr::checked_output_bytes(pixels.capacity() as u64, 16, 0, limits)? as u64;
|
||||
+ super::linear_exr::checked_stage_bytes(count, 24, retained, limits)?;
|
||||
let horizontal = allocate(pixels.len())?;
|
||||
+ let horizontal_bytes = super::linear_exr::checked_output_bytes(horizontal.capacity() as u64, 12, 0, limits)? as u64;
|
||||
+ let retained = retained.checked_add(horizontal_bytes).ok_or_else(|| invalid("bloom retained byte overflow"))?;
|
||||
+ super::linear_exr::checked_stage_bytes(count, 12, retained, limits)?;
|
||||
let vertical = allocate(pixels.len())?;
|
||||
+ super::linear_exr::checked_output_bytes(vertical.capacity() as u64, 12, 0, limits)?;
|
||||
+ super::linear_exr::checked_stage_bytes(vertical.capacity() as u64, 12, retained, limits)?;
|
||||
Ok(Self { pixels, horizontal, vertical, width: width as usize, height: height as usize, options, cancel, phase: 0, line: 0 })
|
||||
}
|
||||
pub fn total_lines(&self) -> u64 {
|
||||
@@ -247,4 +263,36 @@
|
||||
assert!(task.step(1).is_err());
|
||||
assert!(task.finish().is_err());
|
||||
}
|
||||
-}
|
||||
+
|
||||
+ #[test]
|
||||
+ fn explicit_bloom_preserves_independent_three_box_kernel_and_quantum() {
|
||||
+ let mut pixels = vec![[0.0, 0.0, 0.0, 1.0]; 121]; pixels[60][0] = 1.0;
|
||||
+ let options = Bloom { strength: 1.0, threshold: 0.0, radius: 1 };
|
||||
+ let mut work = BloomTask::new_with_limits(11, 11, pixels.clone(), options, CancelToken::default(), GPU_PATH_LIMITS).unwrap();
|
||||
+ while !work.step(1).unwrap() {}
|
||||
+ let (retained, glow) = work.finish().unwrap();
|
||||
+ assert_eq!(retained, pixels);
|
||||
+ let kernel = [1.0, 3.0, 6.0, 7.0, 6.0, 3.0, 1.0];
|
||||
+ for y in 0..11 { for x in 0..11 {
|
||||
+ let expected = if (2..=8).contains(&x) && (2..=8).contains(&y) { kernel[x-2] * kernel[y-2] / 729.0 } else { 0.0 };
|
||||
+ assert!((f64::from(glow[y*11+x][0]) - expected).abs() < 2e-7);
|
||||
+ assert_eq!(&glow[y*11+x][1..], &[0.0, 0.0]);
|
||||
+ } }
|
||||
+ assert_eq!(glow, run(pixels, 11, 11, 1, 32));
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn wide_bloom_is_explicit_and_legacy_inactive_and_cancel_order_stay_intact() {
|
||||
+ let wide = super::super::CpuBudget::Workstation.image_limits(false);
|
||||
+ let options = Bloom { strength: 1.0, ..Default::default() };
|
||||
+ assert!(BloomTask::new(8193, 1, vec![], options, CancelToken::default()).is_err());
|
||||
+ let cancel = CancelToken::default();
|
||||
+ let mut task = BloomTask::new_with_limits(8193, 1, vec![[0.0, 0.0, 0.0, 1.0]; 8193], options, cancel.clone(), wide).unwrap();
|
||||
+ cancel.cancel();
|
||||
+ assert_eq!(task.step(1).unwrap_err().code, ErrorCode::Cancelled);
|
||||
+ assert_eq!(Bloom::default().scratch_bytes(0, u32::MAX).unwrap(), 0);
|
||||
+ assert_eq!(options.scratch_bytes(8193, 1).unwrap(), 8193 * 24, "legacy estimate remains arithmetic-only");
|
||||
+ assert_eq!(BloomTask::new(0, 1, vec![], options, cancel.clone()).err().unwrap().code, ErrorCode::Cancelled);
|
||||
+ assert_eq!(BloomTask::new(0, 1, vec![], Bloom { strength: f64::NAN, ..options }, cancel).err().unwrap().code, ErrorCode::InvalidRequest);
|
||||
+ }
|
||||
+}
|
||||
--- a/crates/render/src/job/photographic.rs
|
||||
+++ b/crates/render/src/job/photographic.rs
|
||||
@@ -98,6 +98,12 @@
|
||||
}
|
||||
count.checked_mul(8).and_then(|n| n.checked_add(16_384)).ok_or_else(|| invalid("photographic scratch size overflow"))
|
||||
}
|
||||
+ pub(crate) fn scratch_bytes_with_limits(self, width: u32, height: u32, limits: crate::RenderLimits) -> Result<u64> {
|
||||
+ self.validate()?;
|
||||
+ let count = super::linear_exr::output_pixels_with_limits(width, height, limits)?;
|
||||
+ if !self.active() { return Ok(0); }
|
||||
+ super::linear_exr::checked_stage_bytes(count, 8, 16_384, limits)
|
||||
+ }
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct Highlight {
|
||||
@@ -114,6 +120,22 @@
|
||||
impl PhotographicTask {
|
||||
pub fn new(width: u32, height: u32, source: Vec<u8>, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken) -> Result<Self> {
|
||||
options.scratch_bytes(width, height)?;
|
||||
+ Self::create(width, height, source, linear, options, cancel, GPU_PATH_LIMITS)
|
||||
+ }
|
||||
+ pub(crate) fn new_with_limits(width: u32, height: u32, source: Vec<u8>, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken, limits: crate::RenderLimits) -> Result<Self> {
|
||||
+ options.scratch_bytes_with_limits(width, height, limits)?;
|
||||
+ cancel.check()?;
|
||||
+ let count = super::linear_exr::output_pixels_with_limits(width, height, limits)?;
|
||||
+ if usize::try_from(count).ok() != Some(linear.len()) || linear.len().checked_mul(4) != Some(source.len()) || !options.active() {
|
||||
+ return Err(invalid("photographic stage requires an admitted opaque image, matching source pixels and an active effect"));
|
||||
+ }
|
||||
+ let raw_bytes = super::linear_exr::checked_output_bytes(linear.capacity() as u64, 16, 0, limits)? as u64;
|
||||
+ let source_bytes = super::linear_exr::checked_output_bytes(source.capacity() as u64, 1, 0, limits)? as u64;
|
||||
+ let retained = raw_bytes.checked_add(source_bytes).and_then(|n| n.checked_add(16_384)).ok_or_else(|| invalid("photographic retained byte overflow"))?;
|
||||
+ super::linear_exr::checked_stage_bytes(count, 4, retained, limits)?;
|
||||
+ Self::create(width, height, source, linear, options, cancel, limits)
|
||||
+ }
|
||||
+ fn create(width: u32, height: u32, source: Vec<u8>, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken, limits: crate::RenderLimits) -> Result<Self> {
|
||||
if std::mem::size_of::<PhotographicState>() > 16_384 {
|
||||
return Err(invalid("photographic metadata exceeds its admitted allowance"));
|
||||
}
|
||||
@@ -122,7 +144,7 @@
|
||||
if state.capacity() != 1 {
|
||||
return Err(invalid("photographic state exceeds bounded capacity"));
|
||||
}
|
||||
- state.push(PhotographicState::new(width, height, source, linear, options, cancel)?);
|
||||
+ state.push(PhotographicState::new(width, height, source, linear, options, cancel, limits)?);
|
||||
Ok(Self { state })
|
||||
}
|
||||
pub fn step(&mut self, units: usize) -> Result<bool> {
|
||||
@@ -153,21 +175,23 @@
|
||||
ready: bool,
|
||||
}
|
||||
impl PhotographicState {
|
||||
- pub fn new(width: u32, height: u32, source: Vec<u8>, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken) -> Result<Self> {
|
||||
+ pub fn new(width: u32, height: u32, source: Vec<u8>, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken, limits: crate::RenderLimits) -> Result<Self> {
|
||||
options.validate()?;
|
||||
cancel.check()?;
|
||||
let count = u64::from(width) * u64::from(height);
|
||||
if width == 0
|
||||
|| height == 0
|
||||
- || u64::from(width) > GPU_PATH_LIMITS.max_dimension
|
||||
- || u64::from(height) > GPU_PATH_LIMITS.max_dimension
|
||||
- || count > GPU_PATH_LIMITS.max_pixels
|
||||
+ || super::linear_exr::output_pixels_with_limits(width, height, limits).is_err()
|
||||
|| usize::try_from(count).ok() != Some(linear.len())
|
||||
|| linear.len().checked_mul(4) != Some(source.len())
|
||||
|| !options.active()
|
||||
{
|
||||
return Err(invalid("photographic stage requires an admitted opaque image, matching source pixels and an active effect"));
|
||||
}
|
||||
+ let raw_bytes = super::linear_exr::checked_output_bytes(linear.capacity() as u64, 16, 0, limits)? as u64;
|
||||
+ let source_bytes = super::linear_exr::checked_output_bytes(source.capacity() as u64, 1, 0, limits)? as u64;
|
||||
+ let retained = raw_bytes.checked_add(source_bytes).and_then(|n| n.checked_add(16_384)).ok_or_else(|| invalid("photographic retained byte overflow"))?;
|
||||
+ super::linear_exr::checked_stage_bytes(count, 4, retained, limits)?;
|
||||
let mut output = Vec::new();
|
||||
output.try_reserve_exact(source.len()).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "photographic output allocation failed"))?;
|
||||
if output.capacity() != source.len() {
|
||||
@@ -449,4 +473,35 @@
|
||||
assert!(task.step(1).is_err());
|
||||
assert!(serde_json::from_str::<Photographic>(r#"{"physical_lens":true}"#).is_err());
|
||||
}
|
||||
-}
|
||||
+
|
||||
+ #[test]
|
||||
+ fn explicit_wide_photographic_keeps_constants_and_legacy_refusal() {
|
||||
+ let wide = super::super::CpuBudget::Workstation.image_limits(false);
|
||||
+ let options = Photographic { radial_distortion: 0.1, chromatic_pixels: 2.0, soft_focus: 0.3, sharpening: 0.2, ..Default::default() };
|
||||
+ assert!(PhotographicTask::new(8193, 1, vec![], vec![], options, CancelToken::default()).is_err());
|
||||
+ let rgba = [128, 128, 128, 255].repeat(8193);
|
||||
+ let mut task = PhotographicTask::new_with_limits(8193, 1, rgba.clone(), vec![[0.25, 0.25, 0.25, 1.0]; 8193], options, CancelToken::default(), wide).unwrap();
|
||||
+ while !task.step(256).unwrap() {}
|
||||
+ assert_eq!(task.finish().unwrap(), rgba);
|
||||
+ let cancel = CancelToken::default(); cancel.cancel();
|
||||
+ assert_eq!(Photographic::default().scratch_bytes(0, u32::MAX).unwrap(), 0);
|
||||
+ assert_eq!(PhotographicTask::new(0, 1, vec![], vec![], options, cancel.clone()).err().unwrap().code, ErrorCode::InvalidRequest);
|
||||
+ assert_eq!(PhotographicTask::new(0, 1, vec![], vec![], Photographic::default(), cancel).err().unwrap().code, ErrorCode::Cancelled);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn explicit_gpu_photographic_matches_legacy_and_cancel_never_finishes() {
|
||||
+ let options = Photographic { grain: 0.03, seed: 37, ..Default::default() };
|
||||
+ let rgba = [64, 128, 192, 255].repeat(6);
|
||||
+ let linear = vec![[0.1, 0.5, 2.0, 1.0]; 6];
|
||||
+ let mut legacy = PhotographicTask::new(3, 2, rgba.clone(), linear.clone(), options, CancelToken::default()).unwrap();
|
||||
+ let mut explicit = PhotographicTask::new_with_limits(3, 2, rgba.clone(), linear.clone(), options, CancelToken::default(), GPU_PATH_LIMITS).unwrap();
|
||||
+ while !legacy.step(1).unwrap() {} while !explicit.step(16).unwrap() {}
|
||||
+ assert_eq!(legacy.finish().unwrap(), explicit.finish().unwrap());
|
||||
+ let cancel = CancelToken::default();
|
||||
+ let mut task = PhotographicTask::new_with_limits(3, 2, rgba, linear, options, cancel.clone(), GPU_PATH_LIMITS).unwrap();
|
||||
+ cancel.cancel();
|
||||
+ assert_eq!(task.step(1).unwrap_err().code, ErrorCode::Cancelled);
|
||||
+ assert_eq!(task.finish().err().unwrap().code, ErrorCode::Cancelled);
|
||||
+ }
|
||||
+}
|
||||
--- a/crates/render/src/job/linear_exr.rs
|
||||
+++ b/crates/render/src/job/linear_exr.rs
|
||||
@@ -14,7 +14,70 @@
|
||||
if w == 0 || h == 0 || w > 8192 || h > 8192 || w * h > 16_777_216 {
|
||||
return Err(invalid("linear EXR requires 1..8192 sides and at most 16777216 pixels"));
|
||||
}
|
||||
- Ok(w * h * 16 + h * 16 + 4096)
|
||||
+ encoded_limit_with_limits(width, height, super::GPU_PATH_LIMITS)
|
||||
+}
|
||||
+
|
||||
+/// Internal bounded policy, not proof of a host reservation. Future callers must
|
||||
+/// retain their request's lease and charge work before advancing output stages.
|
||||
+pub(crate) fn output_pixels_with_limits(width: u32, height: u32, limits: crate::RenderLimits) -> Result<u64> {
|
||||
+ let maximum = super::CpuBudget::Workstation.image_limits(false);
|
||||
+ if limits.max_dimension > maximum.max_dimension || limits.max_pixels > maximum.max_pixels
|
||||
+ || limits.max_scratch_bytes > maximum.max_scratch_bytes
|
||||
+ {
|
||||
+ return Err(invalid("output policy exceeds the bounded implementation envelope"));
|
||||
+ }
|
||||
+ let (w, h) = (u64::from(width), u64::from(height));
|
||||
+ if limits.fit(w, h, None) != Some((w, h)) {
|
||||
+ return Err(invalid("output dimensions exceed the explicit policy"));
|
||||
+ }
|
||||
+ let pixels = w.checked_mul(h).ok_or_else(|| invalid("output pixel count overflow"))?;
|
||||
+ checked_output_bytes(pixels, 1, 0, limits)?;
|
||||
+ Ok(pixels)
|
||||
+}
|
||||
+
|
||||
+/// Checked combined live-byte estimate; this is not an individual Vec layout or a lease.
|
||||
+pub(crate) fn checked_stage_bytes(count: u64, element_bytes: u64, extra: u64, limits: crate::RenderLimits) -> Result<u64> {
|
||||
+ let maximum = super::CpuBudget::Workstation.image_limits(false);
|
||||
+ if limits.max_dimension > maximum.max_dimension || limits.max_pixels > maximum.max_pixels
|
||||
+ || limits.max_scratch_bytes > maximum.max_scratch_bytes
|
||||
+ {
|
||||
+ return Err(invalid("output policy exceeds the bounded implementation envelope"));
|
||||
+ }
|
||||
+ let bytes = count.checked_mul(element_bytes).and_then(|n| n.checked_add(extra))
|
||||
+ .ok_or_else(|| invalid("output byte layout overflow"))?;
|
||||
+ if bytes > limits.max_scratch_bytes {
|
||||
+ return Err(invalid("output byte layout exceeds its explicit policy"));
|
||||
+ }
|
||||
+ Ok(bytes)
|
||||
+}
|
||||
+
|
||||
+/// Check an individual addressable byte layout separately from combined estimates.
|
||||
+pub(crate) fn checked_output_bytes(count: u64, element_bytes: u64, extra: u64, limits: crate::RenderLimits) -> Result<usize> {
|
||||
+ let bytes = checked_stage_bytes(count, element_bytes, extra, limits)?;
|
||||
+ let addressable = usize::try_from(bytes).map_err(|_| invalid("output byte layout exceeds address space"))?;
|
||||
+ if std::alloc::Layout::array::<u8>(addressable).is_err() {
|
||||
+ return Err(invalid("output byte layout exceeds address space"));
|
||||
+ }
|
||||
+ Ok(addressable)
|
||||
+}
|
||||
+
|
||||
+pub(crate) fn encoded_limit_with_limits(width: u32, height: u32, limits: crate::RenderLimits) -> Result<u64> {
|
||||
+ let pixels = output_pixels_with_limits(width, height, limits)?;
|
||||
+ let row_bytes = u64::from(width).checked_mul(16).ok_or_else(|| invalid("EXR row overflow"))?;
|
||||
+ i32::try_from(row_bytes).map_err(|_| invalid("EXR row exceeds scanline representation"))?;
|
||||
+ i32::try_from(width).and_then(|_| i32::try_from(height)).map_err(|_| invalid("EXR window exceeds integer representation"))?;
|
||||
+ let extra = u64::from(height).checked_mul(16).and_then(|n| n.checked_add(4096)).ok_or_else(|| invalid("EXR metadata overflow"))?;
|
||||
+ Ok(checked_output_bytes(pixels, 16, extra, limits)? as u64)
|
||||
+}
|
||||
+
|
||||
+pub(crate) fn scanline_layout(width: u32, height: u32, header_bytes: usize, limits: crate::RenderLimits) -> Result<(usize, usize)> {
|
||||
+ let limit = encoded_limit_with_limits(width, height, limits)?;
|
||||
+ let rows = usize::try_from(height).map_err(|_| invalid("EXR row count exceeds address space"))?;
|
||||
+ let row = usize::try_from(width).ok().and_then(|n| n.checked_mul(16)).ok_or_else(|| invalid("EXR row layout overflow"))?;
|
||||
+ let first = rows.checked_mul(8).and_then(|n| n.checked_add(header_bytes)).ok_or_else(|| invalid("EXR offset table overflow"))?;
|
||||
+ let total = row.checked_add(8).and_then(|n| n.checked_mul(rows)).and_then(|n| n.checked_add(first)).ok_or_else(|| invalid("EXR scanline layout overflow"))?;
|
||||
+ if total as u64 > limit { return Err(invalid("EXR output exceeds its admission")); }
|
||||
+ Ok((first, total))
|
||||
}
|
||||
|
||||
fn attribute(out: &mut Vec<u8>, name: &[u8], kind: &[u8], value: &[u8]) -> Result<()> {
|
||||
@@ -32,6 +95,12 @@
|
||||
}
|
||||
|
||||
pub(super) fn header(width: u32, height: u32) -> Result<Vec<u8>> {
|
||||
+ encoded_limit(width, height)?;
|
||||
+ header_with_limits(width, height, super::GPU_PATH_LIMITS)
|
||||
+}
|
||||
+
|
||||
+pub(crate) fn header_with_limits(width: u32, height: u32, limits: crate::RenderLimits) -> Result<Vec<u8>> {
|
||||
+ encoded_limit_with_limits(width, height, limits)?;
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(4096).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "EXR header allocation failed"))?;
|
||||
out.extend_from_slice(&20_000_630_u32.to_le_bytes());
|
||||
@@ -83,20 +152,25 @@
|
||||
}
|
||||
impl ExrTask {
|
||||
pub fn new(width: u32, height: u32, pixels: Vec<[f32; 4]>, cancel: CancelToken) -> Result<Self> {
|
||||
- let limit = encoded_limit(width, height)?;
|
||||
+ encoded_limit(width, height)?;
|
||||
+ Self::new_with_limits(width, height, pixels, cancel, super::GPU_PATH_LIMITS)
|
||||
+ }
|
||||
+
|
||||
+ pub(crate) fn new_with_limits(width: u32, height: u32, pixels: Vec<[f32; 4]>, cancel: CancelToken, limits: crate::RenderLimits) -> Result<Self> {
|
||||
+ let limit = encoded_limit_with_limits(width, height, limits)?;
|
||||
if pixels.len() as u64 != u64::from(width) * u64::from(height) {
|
||||
return Err(invalid("EXR pixel count differs from dimensions"));
|
||||
}
|
||||
cancel.check()?;
|
||||
- let mut bytes = header(width, height)?;
|
||||
+ checked_output_bytes(pixels.capacity() as u64, 16, 0, limits)?;
|
||||
+ checked_stage_bytes(pixels.capacity() as u64, 16, limit, limits)?;
|
||||
+ let mut bytes = header_with_limits(width, height, limits)?;
|
||||
let row_bytes = u64::from(width) * 16;
|
||||
- let first = bytes.len() as u64 + u64::from(height) * 8;
|
||||
- let total = first + u64::from(height) * (row_bytes + 8);
|
||||
- if total > limit {
|
||||
- return Err(invalid("EXR output exceeds its admission"));
|
||||
- }
|
||||
- let additional = usize::try_from(total).ok().and_then(|n| n.checked_sub(bytes.len())).ok_or_else(|| invalid("EXR address space exceeded"))?;
|
||||
+ let (first, total) = scanline_layout(width, height, bytes.len(), limits)?;
|
||||
+ let first = first as u64;
|
||||
+ let additional = total.checked_sub(bytes.len()).ok_or_else(|| invalid("EXR address space exceeded"))?;
|
||||
bytes.try_reserve_exact(additional).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "EXR output allocation failed"))?;
|
||||
+ if bytes.capacity() as u64 > limit { return Err(invalid("EXR output exceeds its admission")); }
|
||||
for y in 0..height {
|
||||
bytes.extend_from_slice(&(first + u64::from(y) * (row_bytes + 8)).to_le_bytes());
|
||||
}
|
||||
@@ -197,4 +271,43 @@
|
||||
cancel.cancel();
|
||||
assert_eq!(task.step(1).unwrap_err().code, ErrorCode::Cancelled);
|
||||
}
|
||||
-}
|
||||
+
|
||||
+ #[test]
|
||||
+ fn explicit_output_policy_is_exact_bounded_and_checked_before_allocation() {
|
||||
+ let wide = super::super::CpuBudget::Workstation.image_limits(false);
|
||||
+ assert_eq!(output_pixels_with_limits(8193, 1, wide).unwrap(), 8193);
|
||||
+ assert_eq!(encoded_limit_with_limits(8193, 1, wide).unwrap(), 135200);
|
||||
+ assert_eq!(checked_output_bytes(8193, 8, 65536, wide).unwrap(), 131080);
|
||||
+ for (w, h) in [(0, 1), (1, 0), (u32::MAX, u32::MAX)] {
|
||||
+ assert!(output_pixels_with_limits(w, h, wide).is_err());
|
||||
+ }
|
||||
+ assert!(output_pixels_with_limits(8193, 1, super::super::GPU_PATH_LIMITS).is_err(), "a reduced fit is not acceptance");
|
||||
+ for hostile in [
|
||||
+ crate::RenderLimits { max_dimension: u64::MAX, ..wide },
|
||||
+ crate::RenderLimits { max_pixels: u64::MAX, ..wide },
|
||||
+ crate::RenderLimits { max_scratch_bytes: u64::MAX, ..wide },
|
||||
+ ] {
|
||||
+ assert!(output_pixels_with_limits(1, 1, hostile).is_err());
|
||||
+ }
|
||||
+ assert!(checked_output_bytes(u64::MAX, 16, 0, wide).is_err());
|
||||
+ assert!(checked_output_bytes(1, 1, u64::MAX, wide).is_err());
|
||||
+ assert!(scanline_layout(1, 1, usize::MAX, wide).is_err());
|
||||
+ assert!(checked_output_bytes(1, 16, 0, crate::RenderLimits { max_scratch_bytes: 15, ..wide }).is_err());
|
||||
+ assert!(checked_output_bytes(isize::MAX as u64 + 1, 1, 0, wide).is_err());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn explicit_gpu_exr_keeps_legacy_bytes_and_dimension_before_cancel_order() {
|
||||
+ let pixels = vec![[4.0, 1.0, 0.25, 1.0]; 6];
|
||||
+ let expected = encode(pixels.clone(), 3, 2);
|
||||
+ let mut task = ExrTask::new_with_limits(3, 2, pixels, CancelToken::default(), super::super::GPU_PATH_LIMITS).unwrap();
|
||||
+ assert!(task.step(2).unwrap());
|
||||
+ assert_eq!(task.finish().unwrap().0, expected);
|
||||
+ let cancel = CancelToken::default();
|
||||
+ cancel.cancel();
|
||||
+ let error = ExrTask::new(0, 1, vec![], cancel.clone()).err().unwrap();
|
||||
+ assert_eq!(error.code, ErrorCode::InvalidRequest);
|
||||
+ assert!(error.to_string().contains("linear EXR requires 1..8192"));
|
||||
+ assert_eq!(ExrTask::new(1, 1, vec![], cancel).err().unwrap().code, ErrorCode::InvalidRequest);
|
||||
+ }
|
||||
+}
|
||||
--- a/crates/render/src/job/linear_exr_decode.rs
|
||||
+++ b/crates/render/src/job/linear_exr_decode.rs
|
||||
@@ -17,13 +17,24 @@
|
||||
impl Decoder {
|
||||
pub(super) fn new(bytes: &[u8], width: u32, height: u32, cancel: &CancelToken) -> Result<Self> {
|
||||
cancel.check()?;
|
||||
- let limit = super::linear_exr::encoded_limit(width, height)?;
|
||||
- let expected = super::linear_exr::header(width, height)?;
|
||||
+ super::linear_exr::encoded_limit(width, height)?;
|
||||
+ Self::new_with_limits(bytes, width, height, cancel, super::GPU_PATH_LIMITS)
|
||||
+ }
|
||||
+ pub(crate) fn new_with_limits(bytes: &[u8], width: u32, height: u32, cancel: &CancelToken, limits: crate::RenderLimits) -> Result<Self> {
|
||||
+ cancel.check()?;
|
||||
+ let limit = super::linear_exr::encoded_limit_with_limits(width, height, limits)?;
|
||||
+ let count = super::linear_exr::output_pixels_with_limits(width, height, limits)?;
|
||||
+ super::linear_exr::checked_output_bytes(count, 16, 0, limits)?;
|
||||
+ super::linear_exr::checked_stage_bytes(count, 16, 4096, limits)?;
|
||||
+ let expected = if limits == super::GPU_PATH_LIMITS {
|
||||
+ super::linear_exr::header(width, height)?
|
||||
+ } else {
|
||||
+ super::linear_exr::header_with_limits(width, height, limits)?
|
||||
+ };
|
||||
if bytes.len() as u64 > limit || !bytes.starts_with(&expected) {
|
||||
return Err(invalid("master is not the retained native FLOAT32 linear-sRGB/D65 profile"));
|
||||
}
|
||||
- let first = expected.len() + height as usize * 8;
|
||||
- let length = first + height as usize * (width as usize * 16 + 8);
|
||||
+ let (first, length) = super::linear_exr::scanline_layout(width, height, expected.len(), limits)?;
|
||||
if bytes.len() != length {
|
||||
return Err(invalid("native master has missing or trailing scanline bytes"));
|
||||
}
|
||||
@@ -79,7 +90,8 @@
|
||||
}
|
||||
}
|
||||
fn word(bytes: &[u8], offset: usize) -> Result<u32> {
|
||||
- bytes.get(offset..offset + 4).and_then(|s| s.try_into().ok()).map(u32::from_le_bytes).ok_or_else(|| invalid("truncated native master word"))
|
||||
+ let end = offset.checked_add(4).ok_or_else(|| invalid("native master word offset overflow"))?;
|
||||
+ bytes.get(offset..end).and_then(|s| s.try_into().ok()).map(u32::from_le_bytes).ok_or_else(|| invalid("truncated native master word"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -117,4 +129,22 @@
|
||||
assert!(decoder.step(&bytes, &cancel).is_err());
|
||||
assert_eq!(decoder.rows(), 0);
|
||||
}
|
||||
+
|
||||
+ #[test]
|
||||
+ fn explicit_wide_native_roundtrip_retains_raw_bits_and_legacy_limits() {
|
||||
+ let wide = super::super::CpuBudget::Workstation.image_limits(false);
|
||||
+ let raw = vec![[4.0, 1.0, 0.25, 1.0]; 8193];
|
||||
+ let cancel = CancelToken::default();
|
||||
+ let mut task = super::super::linear_exr::ExrTask::new_with_limits(8193, 1, raw.clone(), cancel.clone(), wide).unwrap();
|
||||
+ assert!(task.step(1).unwrap());
|
||||
+ let (bytes, unchanged) = task.finish().unwrap();
|
||||
+ assert_eq!(unchanged, raw);
|
||||
+ assert!(Decoder::new(&bytes, 8193, 1, &cancel).is_err());
|
||||
+ let mut decoder = Decoder::new_with_limits(&bytes, 8193, 1, &cancel, wide).unwrap();
|
||||
+ assert!(decoder.step(&bytes, &cancel).unwrap());
|
||||
+ assert_eq!(decoder.finish().unwrap(), raw);
|
||||
+ cancel.cancel();
|
||||
+ assert_eq!(Decoder::new(&[], 0, 0, &cancel).err().unwrap().code, ErrorCode::Cancelled);
|
||||
+ assert_eq!(Decoder::new_with_limits(&[], 0, 0, &cancel, wide).err().unwrap().code, ErrorCode::Cancelled);
|
||||
+ }
|
||||
}
|
||||
--- a/crates/render/src/job/png.rs
|
||||
+++ b/crates/render/src/job/png.rs
|
||||
@@ -51,8 +51,20 @@
|
||||
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid PNG dimensions or RGBA length"));
|
||||
}
|
||||
cancel.check()?;
|
||||
+ Self::new_with_limits(request, rgba, cancel, super::GPU_PATH_LIMITS)
|
||||
+ }
|
||||
+ pub(crate) fn new_with_limits(request: &ImageRequest, rgba: Vec<u8>, cancel: CancelToken, limits: crate::RenderLimits) -> Result<Self> {
|
||||
+ let pixels = super::linear_exr::output_pixels_with_limits(request.width, request.height, limits)?;
|
||||
+ let rgba_bytes = super::linear_exr::checked_output_bytes(pixels, 4, 0, limits)?;
|
||||
+ if rgba.len() != rgba_bytes {
|
||||
+ return Err(JobError::new(ErrorCode::InvalidRequest, "invalid PNG dimensions or RGBA length"));
|
||||
+ }
|
||||
+ let limit = super::linear_exr::checked_output_bytes(pixels, 8, 65_536, limits)?;
|
||||
+ let retained = super::linear_exr::checked_output_bytes(rgba.capacity() as u64, 1, 0, limits)? as u64;
|
||||
+ super::linear_exr::checked_stage_bytes(1, retained, limit as u64, limits)?;
|
||||
+ cancel.check()?;
|
||||
let bytes = Arc::new(Mutex::new(Vec::new()));
|
||||
- let output = Output { bytes: bytes.clone(), limit: (pixels * 8 + 65_536) as usize, cancel: cancel.clone() };
|
||||
+ let output = Output { bytes: bytes.clone(), limit, cancel: cancel.clone() };
|
||||
let mut encoder = png::Encoder::new(output, request.width, request.height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
@@ -85,3 +97,43 @@
|
||||
Ok(TaskPoll::Complete(std::mem::take(&mut *bytes)))
|
||||
}
|
||||
}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::*;
|
||||
+
|
||||
+ fn request(width: u32, height: u32) -> ImageRequest {
|
||||
+ ImageRequest { width, height, camera: Default::default(), integrator: Default::default(), raytrace: None,
|
||||
+ environment: None, textures: None, studio_weights: None, background: [0; 3], transparent_background: false }
|
||||
+ }
|
||||
+ fn finish(mut task: PngTask) -> Vec<u8> {
|
||||
+ loop { if let TaskPoll::Complete(bytes) = task.step(1).unwrap() { return bytes; } }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn explicit_png_keeps_default_bytes_and_roundtrips_a_narrow_wide_image() {
|
||||
+ let small = request(3, 2); let rgba = [20, 40, 60, 255].repeat(6);
|
||||
+ let legacy = finish(PngTask::new(&small, rgba.clone(), CancelToken::default()).unwrap());
|
||||
+ let explicit = finish(PngTask::new_with_limits(&small, rgba, CancelToken::default(), super::super::GPU_PATH_LIMITS).unwrap());
|
||||
+ assert_eq!(explicit, legacy);
|
||||
+ let wide = request(8193, 1); let rgba = [20, 40, 60, 255].repeat(8193);
|
||||
+ assert!(PngTask::new(&wide, vec![], CancelToken::default()).is_err());
|
||||
+ let png = finish(PngTask::new_with_limits(&wide, rgba.clone(), CancelToken::default(), super::super::CpuBudget::Workstation.image_limits(false)).unwrap());
|
||||
+ let decoded = image::load_from_memory(&png).unwrap().to_rgba8();
|
||||
+ assert_eq!(decoded.dimensions(), (8193, 1));
|
||||
+ assert_eq!(decoded.as_raw(), &rgba);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn png_dimension_length_and_cancel_precedence_remains_legacy() {
|
||||
+ let cancel = CancelToken::default(); cancel.cancel();
|
||||
+ assert_eq!(PngTask::new(&request(0, 1), vec![], cancel.clone()).err().unwrap().code, ErrorCode::InvalidRequest);
|
||||
+ assert_eq!(PngTask::new(&request(1, 1), vec![], cancel.clone()).err().unwrap().code, ErrorCode::InvalidRequest);
|
||||
+ assert_eq!(PngTask::new(&request(1, 1), vec![0; 4], cancel.clone()).err().unwrap().code, ErrorCode::Cancelled);
|
||||
+ let bad = crate::RenderLimits { max_scratch_bytes: u64::MAX, ..super::super::GPU_PATH_LIMITS };
|
||||
+ assert!(PngTask::new_with_limits(&request(1, 1), vec![0; 4], CancelToken::default(), bad).is_err());
|
||||
+ let cancel = CancelToken::default();
|
||||
+ let mut task = PngTask::new_with_limits(&request(1, 1), vec![0; 4], cancel.clone(), super::super::GPU_PATH_LIMITS).unwrap();
|
||||
+ cancel.cancel(); assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled);
|
||||
+ }
|
||||
+}
|
||||
--- a/crates/render/src/job/regrade.rs
|
||||
+++ b/crates/render/src/job/regrade.rs
|
||||
@@ -7,19 +7,29 @@
|
||||
pub(super) fn required_bytes(source: &RenderFrame, settings: Presentation) -> Result<u64> {
|
||||
settings.validate()?;
|
||||
super::linear_exr::encoded_limit(source.info.width, source.info.height)?;
|
||||
+ required_bytes_with_limits(source, settings, super::GPU_PATH_LIMITS)
|
||||
+}
|
||||
+
|
||||
+pub(crate) fn required_bytes_with_limits(source: &RenderFrame, settings: Presentation, limits: crate::RenderLimits) -> Result<u64> {
|
||||
+ settings.validate()?;
|
||||
+ super::linear_exr::encoded_limit_with_limits(source.info.width, source.info.height, limits)?;
|
||||
if source.linear_exr().is_none() {
|
||||
return Err(JobError::new(ErrorCode::InvalidRequest, "this completed frame has no retained raw linear master"));
|
||||
}
|
||||
- // Includes decoded float4, bloom ping/pong float3 or display bytes, bounded
|
||||
- // PNG output and codec/header/task metadata. The source keeps its own lease.
|
||||
- Ok(u64::from(source.info.width) * u64::from(source.info.height) * 48
|
||||
- + 1_048_576
|
||||
- + settings.finishing.photographic.scratch_bytes(source.info.width, source.info.height)?)
|
||||
+ output_bytes(source.info.width, source.info.height, settings, limits)
|
||||
+}
|
||||
+
|
||||
+fn output_bytes(width: u32, height: u32, settings: Presentation, limits: crate::RenderLimits) -> Result<u64> {
|
||||
+ let pixels = super::linear_exr::output_pixels_with_limits(width, height, limits)?;
|
||||
+ let photo = settings.finishing.photographic.scratch_bytes_with_limits(width, height, limits)?;
|
||||
+ let extra = photo.checked_add(1_048_576).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "regrade byte estimate overflow"))?;
|
||||
+ super::linear_exr::checked_stage_bytes(pixels, 48, extra, limits)
|
||||
}
|
||||
|
||||
pub(super) struct RegradeTask {
|
||||
source: Arc<RenderFrame>,
|
||||
settings: Presentation,
|
||||
+ limits: crate::RenderLimits,
|
||||
cancel: CancelToken,
|
||||
decoder: Option<Decoder>,
|
||||
bloom: Option<BloomTask>,
|
||||
@@ -33,11 +43,20 @@
|
||||
impl RegradeTask {
|
||||
pub(super) fn new(source: Arc<RenderFrame>, settings: Presentation, cancel: CancelToken) -> Result<Self> {
|
||||
required_bytes(&source, settings)?;
|
||||
+ Self::new_with_limits(source, settings, cancel, super::GPU_PATH_LIMITS)
|
||||
+ }
|
||||
+ pub(crate) fn new_with_limits(source: Arc<RenderFrame>, settings: Presentation, cancel: CancelToken, limits: crate::RenderLimits) -> Result<Self> {
|
||||
+ required_bytes_with_limits(&source, settings, limits)?;
|
||||
let raw = source.linear_exr().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "linear master disappeared"))?;
|
||||
- let decoder = Decoder::new(raw, source.info.width, source.info.height, &cancel)?;
|
||||
+ let decoder = if limits == super::GPU_PATH_LIMITS {
|
||||
+ Decoder::new(raw, source.info.width, source.info.height, &cancel)?
|
||||
+ } else {
|
||||
+ Decoder::new_with_limits(raw, source.info.width, source.info.height, &cancel, limits)?
|
||||
+ };
|
||||
Ok(Self {
|
||||
source,
|
||||
settings,
|
||||
+ limits,
|
||||
cancel,
|
||||
decoder: Some(decoder),
|
||||
bloom: None,
|
||||
@@ -81,7 +100,7 @@
|
||||
background: self.settings.background,
|
||||
transparent_background: self.settings.transparent_background,
|
||||
};
|
||||
- self.png = Some(PngTask::new(&request, task.finish()?, self.cancel.clone())?);
|
||||
+ self.png = Some(PngTask::new_with_limits(&request, task.finish()?, self.cancel.clone(), self.limits)?);
|
||||
return self.pending(0, u64::from(height));
|
||||
}
|
||||
if let Some(mut decoder) = self.decoder.take() {
|
||||
@@ -93,7 +112,7 @@
|
||||
}
|
||||
let pixels = decoder.finish()?;
|
||||
if let Some(bloom) = self.settings.finishing.bloom.filter(|b| b.active()) {
|
||||
- self.bloom = Some(BloomTask::new(width, height, pixels, bloom, self.cancel.clone())?);
|
||||
+ self.bloom = Some(BloomTask::new_with_limits(width, height, pixels, bloom, self.cancel.clone(), self.limits)?);
|
||||
return self.pending(0, u64::from(height) * 7);
|
||||
}
|
||||
self.linear = Some(pixels);
|
||||
@@ -124,7 +143,8 @@
|
||||
.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing regrade pixels"))?;
|
||||
let output = self.rgba.get_mut(self.encoded * 4..end * 4).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing regrade output"))?;
|
||||
let glow = self.glow.as_deref().and_then(|g| g.get(self.encoded..end));
|
||||
- self.settings.display(width, height)?.encode_bloom_at(pixels, output, &self.cancel, self.encoded, glow)?;
|
||||
+ self.settings.display_with_limits(width, height, self.limits)?
|
||||
+ .encode_bloom_at_with_limits(pixels, output, &self.cancel, self.encoded, glow, self.limits)?;
|
||||
self.encoded = end;
|
||||
if end < count {
|
||||
return self.pending(end as u64, count as u64);
|
||||
@@ -132,13 +152,14 @@
|
||||
self.glow = None;
|
||||
if self.settings.finishing.photographic.active() {
|
||||
let pixels = self.linear.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing photographic master pixels"))?;
|
||||
- self.photographic = Some(super::photographic::PhotographicTask::new(
|
||||
+ self.photographic = Some(super::photographic::PhotographicTask::new_with_limits(
|
||||
width,
|
||||
height,
|
||||
std::mem::take(&mut self.rgba),
|
||||
pixels,
|
||||
self.settings.finishing.photographic,
|
||||
self.cancel.clone(),
|
||||
+ self.limits,
|
||||
)?);
|
||||
return self.pending(0, u64::from(width) * u64::from(height));
|
||||
}
|
||||
@@ -155,7 +176,22 @@
|
||||
background: self.settings.background,
|
||||
transparent_background: self.settings.transparent_background,
|
||||
};
|
||||
- self.png = Some(PngTask::new(&request, std::mem::take(&mut self.rgba), self.cancel.clone())?);
|
||||
+ self.png = Some(PngTask::new_with_limits(&request, std::mem::take(&mut self.rgba), self.cancel.clone(), self.limits)?);
|
||||
self.pending(0, u64::from(height))
|
||||
}
|
||||
}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::*;
|
||||
+
|
||||
+ #[test]
|
||||
+ fn regrade_size_estimate_is_explicit_checked_and_does_not_grant_a_lease() {
|
||||
+ let wide = super::super::CpuBudget::Workstation.image_limits(false);
|
||||
+ assert_eq!(output_bytes(8193, 1, Presentation::default(), wide).unwrap(), 8193 * 48 + 1_048_576);
|
||||
+ assert!(output_bytes(8193, 1, Presentation::default(), super::super::GPU_PATH_LIMITS).is_err());
|
||||
+ assert!(output_bytes(u32::MAX, u32::MAX, Presentation::default(), wide).is_err());
|
||||
+ assert!(output_bytes(1, 1, Presentation::default(), crate::RenderLimits { max_scratch_bytes: u64::MAX, ..wide }).is_err());
|
||||
+ assert!(output_bytes(1, 1, Presentation::default(), crate::RenderLimits { max_scratch_bytes: 1_048_576, ..wide }).is_err());
|
||||
+ }
|
||||
+}
|
||||
Reference in new issue
Block a user