@photivra/engine 2.8.0 → 2.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -5
- package/CITATION.cff +1 -1
- package/README.md +6 -6
- package/SECURITY.md +1 -1
- package/dist/capture/export-jpeg.js +25 -12
- package/dist/capture/export-jpeg.js.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/core/version.js.map +1 -1
- package/dist/facade/diffraction-provider.js +3 -10
- package/dist/facade/diffraction-provider.js.map +1 -1
- package/dist/facade/expected-signal-setup.d.ts +1 -1
- package/dist/facade/expected-signal-setup.js +2 -6
- package/dist/facade/expected-signal-setup.js.map +1 -1
- package/dist/facade/simulate-capture.js +49 -17
- package/dist/facade/simulate-capture.js.map +1 -1
- package/dist/optics/site-diffraction-kernel.d.ts +5 -0
- package/dist/optics/site-diffraction-kernel.js +32 -0
- package/dist/optics/site-diffraction-kernel.js.map +1 -0
- package/dist/output/print-jpeg.js +70 -42
- package/dist/output/print-jpeg.js.map +1 -1
- package/docs/API_REFERENCE.md +1 -1
- package/docs/api/core-version.md +1 -1
- package/docs/api/exports.json +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,14 +1,39 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 2.8.1 — unreleased (prepared October 25, 2026)
|
|
4
|
+
|
|
5
|
+
A patch release: the same results as 2.8.0, faster. It fixes a 2.8.0 slowdown before a chart or material capture's first RAW tile and writes JPEGs about 3× faster.
|
|
6
|
+
- **Captures:** a 768-pixel Quality capture takes 5.6 s instead of 23.4 s on 2.8.0 (796 s on 2.7.0), and the slowest first tile measured takes 2.2 s instead of 24 s (Node, one thread).
|
|
7
|
+
- **JPEG:** a 24 MP JPEG is written in 5.0 s instead of 15.2 s, with byte-identical files.
|
|
8
|
+
- **No API change:** root exports are unchanged; results are the bytes of 2.8.0.
|
|
4
9
|
|
|
5
10
|
### Faster, same output
|
|
6
11
|
|
|
7
|
-
- **
|
|
8
|
-
- **
|
|
9
|
-
- **
|
|
12
|
+
- **JPEG writing about 3× faster, the same bytes.** A 24 MP baseline JPEG took 15.2 s to write and now takes 5.0 s (Node, one thread); every file is byte-identical.
|
|
13
|
+
- **1:1 Print JPEG:** where the output size equals the crop, each output pixel is one source pixel with weight exactly 1, so its sample is a function of its 8-bit code alone; `createPrintJpegTask` now takes it from a 256-entry table instead of the area-average accumulation.
|
|
14
|
+
- **DCT:** the encoder computes the eight v coefficients of a column in one pass over the block. Each coefficient still adds the same IEEE products in the same order and is scaled in the same order, so the coefficients are identical.
|
|
15
|
+
- **Checked:** identical SHA-256 of the files against 2.8.0 for 6000 × 4000, 1001 × 757, 9 × 7, 256 × 32 and 1543 × 1 images (smooth and noise); all JPEG hash locks pass.
|
|
16
|
+
|
|
17
|
+
- **Captures of chart and material scenes: a short start again (fixes a 2.8.0 slowdown before the first RAW tile).**
|
|
18
|
+
- **Cause:** the tabulated path's four verification sites ran the full chain through the diffraction convolution windowed to the whole render, so its first band convolved the full width before any tile: 24 s for a Quality preview of the 5.6 mm phone sensor at 768 pixels and f/32, against 0.55 s on 2.7.0.
|
|
19
|
+
- **What changed:**
|
|
20
|
+
- the verification uses a convolution windowed to its own 2 × 2 block, whose values are bit-identical to the whole render's (the window contract of 2.6);
|
|
21
|
+
- the whole-render convolution is built only when the environment path runs;
|
|
22
|
+
- the per-channel spectral responses are planned once per channel and kept across calls with the same sensor, exposure and optics;
|
|
23
|
+
- one wavelength's diffraction kernel is resolved once per PSF record, shared by the convolution and the tabulated signal.
|
|
24
|
+
- **Same values:** a capture with warm caches, after another request, equals the same capture from a fresh start (new test); all hash locks pass.
|
|
25
|
+
- **Measured** in Node, one thread, the app's requests tiled as the app renders them (24 MP full frame, f/8, unless noted), 2.8.0 → this change (2.7.0 for reference):
|
|
26
|
+
|
|
27
|
+
| Request | 2.7.0 | 2.8.0 | Now |
|
|
28
|
+
| --- | --- | --- | --- |
|
|
29
|
+
| 48-pixel quick frame, Speed / Quality | 1.3 / 8.3 s | 0.87 / 5.5 s | 0.70 / 4.6 s |
|
|
30
|
+
| 384-pixel capture, Speed / Quality | 43.9 / 193 s | 3.0 / 9.3 s | 1.1 / 2.4 s |
|
|
31
|
+
| 768-pixel capture, Speed / Quality | 185 / 796 s | 11.5 / 23.4 s | 3.3 / 5.6 s |
|
|
32
|
+
| 384-pixel Quality capture, 5.6 mm phone sensor, f/32 | 267 s | 25.4 s | 3.9 s |
|
|
33
|
+
|
|
34
|
+
The 768-pixel Quality preview of that phone sensor at f/32 reaches its first RAW tile in 2.2 s (0.89 s on a repeated call) instead of 24 s.
|
|
10
35
|
|
|
11
|
-
## 2.8.0 —
|
|
36
|
+
## 2.8.0 — published October 25, 2026
|
|
12
37
|
|
|
13
38
|
A minor release that makes full-resolution captures of chart and material scenes about 50× faster (48–84× in the regions measured), and makes the display view exact at device-pixel sizes.
|
|
14
39
|
- **Faster captures, same bytes:** for chart presets and caller material scenes with a still, rectilinear camera, the RAW stage takes tabulated expected electrons and skips the per-site record pipeline. On every request tested, the samples, RAW codes and files are the bytes of 2.7.0.
|
|
@@ -61,6 +86,9 @@ Measured on one thread (24 MP frame, 6 µm, 50 mm f/8, 2 × 2 pixel averaging),
|
|
|
61
86
|
| Siemens star as a caller material scene | 58.6 → 7.1 s (8.3×) | 252.9 → 40.4 s (6.3×) |
|
|
62
87
|
|
|
63
88
|
The material scene gains more because it now also takes the engine-built evaluator's shorter result parsing that chart presets had since 2.6.
|
|
89
|
+
- **Display view: a sample's terms written in place; the clock read less often.** Each real pixel's recorded terms went through a new typed-array view (`subarray`, then `fill`) and `Date.now()` was read per display pixel. The terms are now written straight into the real pixel's memo slot (a scratch buffer only for the first sample of a one-material key), and the clock is read every 16 display pixels and at each row's end; yield timing never changes the output.
|
|
90
|
+
- **Same values:** 57 display views (Speed, a 2 × 2 box aperture and the Quality options; three presets, a caller material scene and a caller function scene; exact and stratified sizes) hash identically before and after: samples, expected values, noise and diagnostics. All hash locks pass.
|
|
91
|
+
- **Measured:** four 32-row bands of the app's 2028 × 1352 view of a 24 MP frame (a caller material scene, Speed, 2 × 2 box aperture), one thread, median of five alternating runs: 4.31 s → 4.00 s (about 7 %). A line profile puts the rest of the time in the per-real-pixel statistics and the scene's material lookups (the caller's `materialAt` with the frozen point it receives), which these changes leave as they are.
|
|
64
92
|
|
|
65
93
|
### Changed
|
|
66
94
|
|
package/CITATION.cff
CHANGED
|
@@ -9,7 +9,7 @@ abstract: "An open TypeScript engine for the science and mathematics of photogra
|
|
|
9
9
|
repository-code: "https://github.com/photivra/photivra"
|
|
10
10
|
url: "https://photivra.com"
|
|
11
11
|
license: "Apache-2.0"
|
|
12
|
-
version: "2.8.
|
|
12
|
+
version: "2.8.1"
|
|
13
13
|
keywords:
|
|
14
14
|
- photography
|
|
15
15
|
- camera optics
|
package/README.md
CHANGED
|
@@ -32,10 +32,10 @@ The source is licensed under Apache-2.0.
|
|
|
32
32
|
|
|
33
33
|
## Quick start
|
|
34
34
|
|
|
35
|
-
Install the published ESM package below. The [2.8.
|
|
35
|
+
Install the published ESM package below. The [2.8.1 release record](https://github.com/Photivra/photivra/blob/main/docs/RELEASE_2_8_1.md) and [changelog](https://github.com/Photivra/photivra/blob/main/CHANGELOG.md) describe the current release:
|
|
36
36
|
|
|
37
37
|
```sh
|
|
38
|
-
npm install @photivra/engine@2.8.
|
|
38
|
+
npm install @photivra/engine@2.8.1
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
Simulate a photograph of a test chart with a generic camera, then read the developed sRGB pixels:
|
|
@@ -75,7 +75,7 @@ console.log(horizontal.provenance);
|
|
|
75
75
|
|
|
76
76
|
Start with the [Developer Guide](https://github.com/Photivra/photivra/blob/main/docs/DEVELOPERS.md). Then use the [Usage Guide](https://github.com/Photivra/photivra/blob/main/docs/USAGE.md) and the [API reference](https://github.com/Photivra/photivra/blob/main/docs/API_REFERENCE.md), which is generated from the package exports.
|
|
77
77
|
|
|
78
|
-
Repository `main` may describe newer, unreleased work. For the stable contract, use the docs bundled in the published package, or the exact `v2.8.
|
|
78
|
+
Repository `main` may describe newer, unreleased work. For the stable contract, use the docs bundled in the published package, or the exact `v2.8.1` tag.
|
|
79
79
|
|
|
80
80
|
## Documentation
|
|
81
81
|
|
|
@@ -363,13 +363,13 @@ The application can then use those results, while the photography calculations t
|
|
|
363
363
|
|
|
364
364
|
## Status
|
|
365
365
|
|
|
366
|
-
- Repository package version: `2.8.
|
|
367
|
-
- Engine API contract: `2.8.
|
|
366
|
+
- Repository package version: `2.8.1` (release candidate prepared October 25, 2026; publication is separate)
|
|
367
|
+
- Engine API contract: `2.8.1`
|
|
368
368
|
- Versioned generic tier reference assets: [GENERIC_TIER_PRESETS.md](https://github.com/Photivra/photivra/blob/main/docs/GENERIC_TIER_PRESETS.md).
|
|
369
369
|
- Composed POC simulation API contract: `1.0.0`
|
|
370
370
|
- Stability: 1.0 root-package compatibility policy; bounded scientific models and independent POC contract
|
|
371
371
|
|
|
372
|
-
From 1.0.1, the package version and `ENGINE_API_VERSION` are equal. New captures/plans record 2.8.
|
|
372
|
+
From 1.0.1, the package version and `ENGINE_API_VERSION` are equal. New captures/plans record 2.8.1; existing archives keep their original creator identities. Schema, model and POC contract versions stay independent.
|
|
373
373
|
|
|
374
374
|
A breaking change to the root contracts now needs a new package major version. Additive and corrective changes follow [compatibility and migration](https://github.com/Photivra/photivra/blob/main/docs/RELEASE_1_3_0.md). A 1.0 package is not a claim of calibrated physical accuracy.
|
|
375
375
|
|
package/SECURITY.md
CHANGED
|
@@ -4,7 +4,7 @@ Please do not open a public issue that contains vulnerability details.
|
|
|
4
4
|
|
|
5
5
|
## Supported versions
|
|
6
6
|
|
|
7
|
-
The published 1.0.0 release started the 1.x root-package compatibility line, and 2.0.0 started the 2.x line. The current release is **2.
|
|
7
|
+
The published 1.0.0 release started the 1.x root-package compatibility line, and 2.0.0 started the 2.x line. The current release is **2.8.0**, published on October 25, 2026 (see [CHANGELOG.md](CHANGELOG.md)).
|
|
8
8
|
|
|
9
9
|
Security fixes target the current maintained development and release line. Do not assume that older 1.x releases, snapshots or pre-1.0 releases will receive fixes.
|
|
10
10
|
|
|
@@ -174,7 +174,7 @@ export function createExportJpegEncoder(input) {
|
|
|
174
174
|
const cosine = JPEG_DCT_COSINES;
|
|
175
175
|
const previous = [0, 0, 0];
|
|
176
176
|
const planes = [new Float64Array(64), new Float64Array(64), new Float64Array(64)];
|
|
177
|
-
const
|
|
177
|
+
const transformed = new Float64Array(64);
|
|
178
178
|
const blueScale = 2 * (1 - .114), redScale = 2 * (1 - .299);
|
|
179
179
|
return {
|
|
180
180
|
writeRgbBlock(samples) {
|
|
@@ -198,20 +198,33 @@ export function createExportJpegEncoder(input) {
|
|
|
198
198
|
const block = planes[channel];
|
|
199
199
|
for (let u = 0; u < 8; u++) {
|
|
200
200
|
const uOffset = u * 8;
|
|
201
|
-
for (let y = 0; y < 8; y++)
|
|
202
|
-
for (let x = 0; x < 8; x++)
|
|
203
|
-
rowProducts[y * 8 + x] = block[y * 8 + x] * cosine[uOffset + x];
|
|
204
201
|
const uFactor = u === 0 ? Math.SQRT1_2 : 1;
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
202
|
+
// The eight v sums in one pass over (y, x): each sum still adds the same products f(x,y)·C(u,x)·C(v,y) in the same
|
|
203
|
+
// order (y, then x), and each row product is the same IEEE product, formed once per (x, y) instead of stored.
|
|
204
|
+
let s0 = 0, s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0, s6 = 0, s7 = 0;
|
|
205
|
+
for (let y = 0; y < 8; y++) {
|
|
206
|
+
const c0 = cosine[y], c1 = cosine[8 + y], c2 = cosine[16 + y], c3 = cosine[24 + y], c4 = cosine[32 + y], c5 = cosine[40 + y], c6 = cosine[48 + y], c7 = cosine[56 + y];
|
|
207
|
+
for (let x = 0; x < 8; x++) {
|
|
208
|
+
const r = block[y * 8 + x] * cosine[uOffset + x];
|
|
209
|
+
s0 += r * c0;
|
|
210
|
+
s1 += r * c1;
|
|
211
|
+
s2 += r * c2;
|
|
212
|
+
s3 += r * c3;
|
|
213
|
+
s4 += r * c4;
|
|
214
|
+
s5 += r * c5;
|
|
215
|
+
s6 += r * c6;
|
|
216
|
+
s7 += r * c7;
|
|
212
217
|
}
|
|
213
|
-
transformed[vOffset + u] = roundJpegCoefficient(sum * .25 * uFactor * (v === 0 ? Math.SQRT1_2 : 1) / q);
|
|
214
218
|
}
|
|
219
|
+
// Scaled as before, left to right: sum·0.25·(u factor)·(v factor)/q.
|
|
220
|
+
transformed[u] = roundJpegCoefficient(s0 * .25 * uFactor * Math.SQRT1_2 / q);
|
|
221
|
+
transformed[8 + u] = roundJpegCoefficient(s1 * .25 * uFactor * 1 / q);
|
|
222
|
+
transformed[16 + u] = roundJpegCoefficient(s2 * .25 * uFactor * 1 / q);
|
|
223
|
+
transformed[24 + u] = roundJpegCoefficient(s3 * .25 * uFactor * 1 / q);
|
|
224
|
+
transformed[32 + u] = roundJpegCoefficient(s4 * .25 * uFactor * 1 / q);
|
|
225
|
+
transformed[40 + u] = roundJpegCoefficient(s5 * .25 * uFactor * 1 / q);
|
|
226
|
+
transformed[48 + u] = roundJpegCoefficient(s6 * .25 * uFactor * 1 / q);
|
|
227
|
+
transformed[56 + u] = roundJpegCoefficient(s7 * .25 * uFactor * 1 / q);
|
|
215
228
|
}
|
|
216
229
|
const difference = transformed[0] - previous[channel], size = amplitude(difference, 11);
|
|
217
230
|
emit(size, 4);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"export-jpeg.js","sourceRoot":"","sources":["../../src/capture/export-jpeg.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;GAKG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,8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AQ,GAAC,IAAI,CAAC,CAAA,CAAC;KACnF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Baseline JPEG encoder written for this project. It computes the DCT (discrete cosine transform)\n * directly and uses no third-party encoder source, default quantization tables or Huffman tables.\n * @see docs/SIMULATED_CAPTURE.md for equations, coordinate/unit conventions, blockers and support\n * limits.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, scaleBudgetCeiling } from \"../core/pixel-limits.js\";\n\n/**\n * Identifies the exact byte output of the baseline encoder.\n *\n * Version 2 (engine 2.0.0) uses the fixed cosine table below instead of runtime `Math.cos`, and rounds\n * quantized coefficients half away from zero. Compared with version 1, bytes can differ only where a\n * coefficient before rounding was within about one ULP (unit in the last place) of a half-integer, or\n * was exactly a negative half-integer. The repository's test images are unchanged.\n */\nexport const EXPORT_JPEG_ENCODER_ID = \"photivra-baseline-jpeg-444-v2\" as const;\n/**\n * C(u,x) = cos((2x+1)·u·π/16) for u,x in 0..7, row-major by u.\n *\n * Each entry is the correctly rounded IEEE-754 double of the exact cosine. They were computed offline with\n * 130-digit decimal arithmetic and checked so that no neighbouring double is closer (see\n * docs/PHOTOGRAPHIC_EXPORT.md). Hard-coding them makes the DCT independent of each JavaScript engine's\n * `Math.cos`, which differs in the last bit between engines. These are mathematical facts, not third-party data.\n */\nexport const JPEG_DCT_COSINES: Readonly<Float64Array> = Float64Array.of(\n 1,1,1,1,1,1,1,1,\n 0.9807852804032304,0.8314696123025452,0.5555702330196022,0.19509032201612828,-0.19509032201612828,-0.5555702330196022,-0.8314696123025452,-0.9807852804032304,\n 0.9238795325112867,0.3826834323650898,-0.3826834323650898,-0.9238795325112867,-0.9238795325112867,-0.3826834323650898,0.3826834323650898,0.9238795325112867,\n 0.8314696123025452,-0.19509032201612828,-0.9807852804032304,-0.5555702330196022,0.5555702330196022,0.9807852804032304,0.19509032201612828,-0.8314696123025452,\n 0.7071067811865476,-0.7071067811865476,-0.7071067811865476,0.7071067811865476,0.7071067811865476,-0.7071067811865476,-0.7071067811865476,0.7071067811865476,\n 0.5555702330196022,-0.9807852804032304,0.19509032201612828,0.8314696123025452,-0.8314696123025452,-0.19509032201612828,0.9807852804032304,-0.5555702330196022,\n 0.3826834323650898,-0.9238795325112867,0.9238795325112867,-0.3826834323650898,-0.3826834323650898,0.9238795325112867,-0.9238795325112867,0.3826834323650898,\n 0.19509032201612828,-0.5555702330196022,0.8314696123025452,-0.9807852804032304,0.9807852804032304,-0.8314696123025452,0.5555702330196022,-0.19509032201612828\n);\n/**\n * Rounds a quantized coefficient to the nearest integer, with ties going away from zero (−2.5 → −3,\n * 2.5 → 3), so positive and negative values round the same way. `Math.round` alone sends −2.5 to −2.\n */\nexport function roundJpegCoefficient(value: number): number {\n return value<0 ? -Math.round(-value) : Math.round(value);\n}\n\n/** Internal baseline JPEG settings: 8-bit YCbCr 4:4:4, one explicit constant quantization step, and uniform Huffman tables written for this project. */\nexport interface ExportJpegInput { width: number; height: number; samples: readonly number[]; quantizationStep: number; exif: Uint8Array; xmp: Uint8Array }\n/** Encodes a baseline JPEG with a directly computed DCT. Uses no third-party encoder source, default quantization tables or Huffman tables. */\nexport function encodeExportJpeg(input: ExportJpegInput): Uint8Array {\n const { width, height, samples, quantizationStep: q } = input;\n if (![width,height,q].every(Number.isSafeInteger) || width < 1 || height < 1 || width*height > 4096 ||\n q < 1 || q > 255 || samples.length !== width*height*3 || Array.from(samples).some((v) => !Number.isInteger(v) || v < 0 || v > 255)) {\n throw new InvalidConfigurationError(\"Unsupported baseline JPEG input.\");\n }\n const encoder=createExportJpegEncoder({...input,maximumOutputBytes:1_000_000});\n for(let by=0;by<height;by+=8)for(let bx=0;bx<width;bx+=8){\n const block:number[]=[];\n for(let y=0;y<8;y++)for(let x=0;x<8;x++){\n const p=(Math.min(by+y,height-1)*width+Math.min(bx+x,width-1))*3;\n block.push(samples[p]!,samples[p+1]!,samples[p+2]!);\n }\n encoder.writeRgbBlock(block);\n }\n return encoder.finish();\n}\n/**\n * Largest byte budget the internal writer accepts: the Print JPEG budget ceiling at the largest opt-in source\n * (256 000 000 bytes per 24 000 000 pixels at 2^27 pixels). Each caller enforces its own smaller budget.\n */\nconst EXPORT_JPEG_MAXIMUM_OUTPUT_BYTES=scaleBudgetCeiling(256_000_000,FULL_RESOLUTION_CEILING_PIXELS);\n/**\n * Internal size-limited JPEG writer. The reference export and the scalable export use exactly the same\n * DCT and entropy-coding equations.\n *\n * When `densityDotsPerInch` is supplied, it is written to the JFIF 1.02 APP0 segment as units=1 (dots\n * per inch) with equal X and Y density. JFIF density fields are 16-bit unsigned, so it must be an integer\n * in 1..65535; callers round any fractional density and store the exact value in EXIF. When omitted,\n * APP0 keeps units=0 with a 1:1 pixel aspect ratio and states no physical size.\n */\nexport function createExportJpegEncoder(input: Omit<ExportJpegInput,\"samples\"> & {maximumOutputBytes:number;icc?:Uint8Array;densityDotsPerInch?:number}): {\n writeRgbBlock(samples:readonly number[]):void; finish():Uint8Array; dispose():void;\n} {\n const {width,height,quantizationStep:q}=input;\n if(![width,height,q,input.maximumOutputBytes].every(Number.isSafeInteger)||width<1||height<1||width>65535||height>65535||q<1||q>255||input.maximumOutputBytes<1||input.maximumOutputBytes>EXPORT_JPEG_MAXIMUM_OUTPUT_BYTES)\n throw new InvalidConfigurationError(\"Invalid bounded JPEG encoding plan.\");\n const density=input.densityDotsPerInch;\n if(density!==undefined&&(!Number.isSafeInteger(density)||density<1||density>65535))\n throw new InvalidConfigurationError(\"JFIF density requires an integer from 1 to 65535 dots per inch.\");\n // Growable output. Capacity starts at min(budget, 64 KiB) and doubles, but never beyond the budget. The budget\n // check is unchanged (offset + n > maximumOutputBytes fails), so the output bytes and failures are the same as\n // with a buffer allocated at full budget up front. An old buffer is zeroed after its bytes are copied over.\n const budget=input.maximumOutputBytes;\n let storage=new Uint8Array(Math.min(budget,65_536)),offset=0,disposed=false,blocks=0;\n const reserve=(count:number):void=>{\n if(disposed||offset+count>budget)throw new InvalidConfigurationError(\"JPEG output exceeds admitted byte budget or is disposed.\");\n if(offset+count<=storage.length)return;\n const grown=new Uint8Array(Math.min(budget,Math.max(storage.length*2,offset+count)));\n grown.set(storage.subarray(0,offset));storage.fill(0,0,offset);storage=grown;\n };\n const push=(...values:number[]):void=>{reserve(values.length);storage.set(values,offset);offset+=values.length;};\n // Fast path for one entropy-coded byte: the same budget/disposal check and byte order as push(), without an array per byte.\n const pushByte=(value:number):void=>{if(disposed||offset>=storage.length)reserve(1);storage[offset++]=value;};\n push(255,216);\n const marker = (id: number, payload: readonly number[]): void => {\n if (payload.length > 65533) throw new InvalidConfigurationError(\"JPEG metadata segment exceeds the standard APP limit.\");\n push(255,id,(payload.length+2)>>8,(payload.length+2)&255,...payload);\n };\n // JFIF 1.02 APP0: identifier, version 1.02, units (0 aspect ratio only, 1 dots per inch), Xdensity, Ydensity, no thumbnail.\n marker(224,density===undefined ? [74,70,73,70,0,1,2,0,0,1,0,1,0,0] : [74,70,73,70,0,1,2,1,density>>8,density&255,density>>8,density&255,0,0]);\n marker(225,[69,120,105,102,0,0,...input.exif]);\n marker(225,[...new TextEncoder().encode(\"http://ns.adobe.com/xap/1.0/\\0\"),...input.xmp]);\n if(input.icc){\n if(input.icc.length>65519)throw new InvalidConfigurationError(\"ICC profile exceeds the single-segment encoding envelope.\");\n marker(226,[...new TextEncoder().encode(\"ICC_PROFILE\\0\"),1,1,...input.icc]);\n }\n marker(219,[0,...Array<number>(64).fill(q)]);\n marker(192,[8,height>>8,height&255,width>>8,width&255,3,1,17,0,2,17,0,3,17,0]);\n // DC categories 0..11 use 4-bit codes; AC EOB/ZRL and all baseline run/category pairs use 8-bit codes.\n // Incomplete canonical Huffman trees reserve the all-ones code, so JPEG bit padding (1-bits) can never be read as a symbol.\n const dc = Array.from({length:12},(_,i) => i), ac = [0,240];\n for (let run=0;run<16;run++) for (let size=1;size<=10;size++) ac.push(run*16+size);\n marker(196,[0,...Array.from({length:16},(_,i) => i===3 ? 12 : 0),...dc,\n 16,...Array.from({length:16},(_,i) => i===7 ? ac.length : 0),...ac]);\n marker(218,[3,1,0,2,0,3,0,0,63,0]);\n let accumulator=0, bits=0;\n // Appends the low `count` bits (count <= 16) most-significant first, emitting each completed byte with 0xFF stuffing.\n const emit = (value: number, count: number): void => {\n accumulator=(accumulator<<count)|(value&((1<<count)-1)); bits+=count;\n while (bits>=8) { bits-=8; const byte=(accumulator>>>bits)&255; pushByte(byte); if (byte===255) pushByte(0); }\n accumulator&=(1<<bits)-1;\n };\n const amplitude = (value: number, max: number): number => {\n const size=value===0 ? 0 : Math.floor(Math.log2(Math.abs(value)))+1;\n if (size>max) throw new InvalidConfigurationError(\"JPEG coefficient exceeds baseline entropy range.\");\n return size;\n };\n const coefficient = (value: number, size: number): void => { if (size) emit(value>=0 ? value : value+(1<<size)-1,size); };\n const zigzag=new Int32Array(64);\n for (let diagonal=0,i=0;diagonal<=14;diagonal++) {\n const points: number[] = [];\n for (let y=0;y<8;y++) { const x=diagonal-y; if (x>=0 && x<8) points.push(y*8+x); }\n for (const point of diagonal%2===0 ? points.reverse() : points) zigzag[i++]=point;\n }\n // Huffman symbol index of each AC (run, size) pair; equals ac.indexOf(symbol) for every emitted symbol.\n const acIndex=new Int16Array(256).fill(-1);\n for (let i=ac.length-1;i>=0;i--) acIndex[ac[i]!]=i;\n/**\n * The 8×8 DCT, computed directly, with orthonormal DC factors and one chosen quantization step.\n *\n * This is a deliberately simple 4:4:4 reference encoder. Lossy quantization means exact RGB pixels are\n * not preserved. Decoding the JPEG and comparing is an interoperability check, not an exact scientific\n * check of pixel values.\n *\n * Each coefficient is the direct 64-term sum Σ_y Σ_x (f(x,y)·C(u,x))·C(v,y), summed over y, then x.\n * The row products f(x,y)·C(u,x) are computed once per u and reused for all eight v. This reuses the\n * identical IEEE-754 products and keeps the exact order of multiplication and summation. A factored\n * row/column DCT would reorder the sum, so it is deliberately not used.\n *\n * C(u,x) comes from the fixed table `JPEG_DCT_COSINES` (correctly rounded constants), not `Math.cos`,\n * so the coefficients do not depend on the JavaScript engine's maths library. Each quantized coefficient\n * is rounded half away from zero (`roundJpegCoefficient`).\n */\n const cosine=JPEG_DCT_COSINES;\n const previous=[0,0,0];\n const planes=[new Float64Array(64),new Float64Array(64),new Float64Array(64)];\n const rowProducts=new Float64Array(64), transformed=new Float64Array(64);\n const blueScale=2*(1-.114), redScale=2*(1-.299);\n return {\n writeRgbBlock(samples:readonly number[]):void {\n let valid=!disposed&&blocks<Math.ceil(width/8)*Math.ceil(height/8)&&samples.length===192;\n for(let i=0;valid&&i<192;i++){const v=samples[i]!;valid=Number.isInteger(v)&&v>=0&&v<=255;}\n if(!valid)throw new InvalidConfigurationError(\"JPEG requires complete bounded RGB coding blocks.\");\n const [luma,blueDifference,redDifference]=planes as [Float64Array,Float64Array,Float64Array];\n for (let i=0;i<64;i++) {\n // JPEG pads only partial 8x8 blocks (MCUs, minimum coded units). The declared image and crop size never change.\n const p=i*3;\n const red=samples[p]!, green=samples[p+1]!, blue=samples[p+2]!, luminance=.299*red+.587*green+.114*blue;\n luma[i]=luminance-128; blueDifference[i]=(blue-luminance)/blueScale; redDifference[i]=(red-luminance)/redScale;\n }\n for (let channel=0;channel<3;channel++) {\n const block=planes[channel]!;\n for (let u=0;u<8;u++) {\n const uOffset=u*8;\n for (let y=0;y<8;y++) for (let x=0;x<8;x++) rowProducts[y*8+x]=block[y*8+x]!*cosine[uOffset+x]!;\n const uFactor=u===0 ? Math.SQRT1_2 : 1;\n for (let v=0;v<8;v++) {\n const vOffset=v*8;\n let sum=0; for (let y=0;y<8;y++) { const cv=cosine[vOffset+y]!; for (let x=0;x<8;x++) sum+=rowProducts[y*8+x]!*cv; }\n transformed[vOffset+u]=roundJpegCoefficient(sum*.25*uFactor*(v===0 ? Math.SQRT1_2 : 1)/q);\n }\n }\n const difference=transformed[0]!-previous[channel]!, size=amplitude(difference,11); emit(size,4); coefficient(difference,size); previous[channel]=transformed[0]!;\n let zeroes=0;\n for (let i=1;i<64;i++) {\n const value=transformed[zigzag[i]!]!;\n if (value===0) { zeroes++; continue; }\n while (zeroes>=16) { emit(1,8); zeroes-=16; }\n const length=amplitude(value,10), symbol=zeroes*16+length; emit(acIndex[symbol]!,8); coefficient(value,length); zeroes=0;\n }\n if (zeroes) emit(0,8);\n }\n blocks++;\n },\n finish():Uint8Array {\n if(disposed||blocks!==Math.ceil(width/8)*Math.ceil(height/8))throw new InvalidConfigurationError(\"JPEG cannot finish incomplete or disposed encoding.\");\n if(bits)emit((1<<(8-bits))-1,8-bits);\n // Only the written prefix can hold data; zero it after the copy instead of filling the whole capacity.\n push(255,217);const output=storage.slice(0,offset);storage.fill(0,0,offset);storage=new Uint8Array(0);disposed=true;return output;\n },\n dispose():void {storage.fill(0,0,offset);storage=new Uint8Array(0);disposed=true;}\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"export-jpeg.js","sourceRoot":"","sources":["../../src/capture/export-jpeg.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;GAKG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7F;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,+BAAwC,CAAC;AAC/E;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAA2B,YAAY,CAAC,EAAE,CACrE,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EACf,kBAAkB,EAAC,kBAAkB,EAAC,kBAAkB,EAAC,mBAAmB,EAAC,CAAC,mBAAmB,EAAC,CAAC,kBAAkB,EAAC,CAAC,kBAAkB,EAAC,CAAC,kBAAkB,EAC7J,kBAAkB,EAAC,kBAAkB,EAAC,CAAC,kBAAkB,EAAC,CAAC,kBAAk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,IAAE,MAAM,KAAG,IAAI,CAAC,IAAI,CAAC,KAAK,GAAC,CAAC,CAAC,GAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAC,CAAC,CAAC;gBAAC,MAAM,IAAI,yBAAyB,CAAC,qDAAqD,CAAC,CAAC;YACxJ,IAAG,IAAI;gBAAC,IAAI,CAAC,CAAC,CAAC,IAAE,CAAC,CAAC,GAAC,IAAI,CAAC,CAAC,GAAC,CAAC,EAAC,CAAC,GAAC,IAAI,CAAC,CAAC;YACrC,uGAAuG;YACvG,IAAI,CAAC,GAAG,EAAC,GAAG,CAAC,CAAC;YAAA,MAAM,MAAM,GAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAC,MAAM,CAAC,CAAC;YAAA,OAAO,CAAC,IAAI,CAAC,CAAC,EAAC,CAAC,EAAC,MAAM,CAAC,CAAC;YAAA,OAAO,GAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;YAAA,QAAQ,GAAC,IAAI,CAAC;YAAA,OAAO,MAAM,CAAC;QACpI,CAAC;QACD,OAAO,KAAS,OAAO,CAAC,IAAI,CAAC,CAAC,EAAC,CAAC,EAAC,MAAM,CAAC,CAAC,CAAA,OAAO,GAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA,QAAQ,GAAC,IAAI,CAAC,CAAA,CAAC;KACnF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Baseline JPEG encoder written for this project. It computes the DCT (discrete cosine transform)\n * directly and uses no third-party encoder source, default quantization tables or Huffman tables.\n * @see docs/SIMULATED_CAPTURE.md for equations, coordinate/unit conventions, blockers and support\n * limits.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, scaleBudgetCeiling } from \"../core/pixel-limits.js\";\n\n/**\n * Identifies the exact byte output of the baseline encoder.\n *\n * Version 2 (engine 2.0.0) uses the fixed cosine table below instead of runtime `Math.cos`, and rounds\n * quantized coefficients half away from zero. Compared with version 1, bytes can differ only where a\n * coefficient before rounding was within about one ULP (unit in the last place) of a half-integer, or\n * was exactly a negative half-integer. The repository's test images are unchanged.\n */\nexport const EXPORT_JPEG_ENCODER_ID = \"photivra-baseline-jpeg-444-v2\" as const;\n/**\n * C(u,x) = cos((2x+1)·u·π/16) for u,x in 0..7, row-major by u.\n *\n * Each entry is the correctly rounded IEEE-754 double of the exact cosine. They were computed offline with\n * 130-digit decimal arithmetic and checked so that no neighbouring double is closer (see\n * docs/PHOTOGRAPHIC_EXPORT.md). Hard-coding them makes the DCT independent of each JavaScript engine's\n * `Math.cos`, which differs in the last bit between engines. These are mathematical facts, not third-party data.\n */\nexport const JPEG_DCT_COSINES: Readonly<Float64Array> = Float64Array.of(\n 1,1,1,1,1,1,1,1,\n 0.9807852804032304,0.8314696123025452,0.5555702330196022,0.19509032201612828,-0.19509032201612828,-0.5555702330196022,-0.8314696123025452,-0.9807852804032304,\n 0.9238795325112867,0.3826834323650898,-0.3826834323650898,-0.9238795325112867,-0.9238795325112867,-0.3826834323650898,0.3826834323650898,0.9238795325112867,\n 0.8314696123025452,-0.19509032201612828,-0.9807852804032304,-0.5555702330196022,0.5555702330196022,0.9807852804032304,0.19509032201612828,-0.8314696123025452,\n 0.7071067811865476,-0.7071067811865476,-0.7071067811865476,0.7071067811865476,0.7071067811865476,-0.7071067811865476,-0.7071067811865476,0.7071067811865476,\n 0.5555702330196022,-0.9807852804032304,0.19509032201612828,0.8314696123025452,-0.8314696123025452,-0.19509032201612828,0.9807852804032304,-0.5555702330196022,\n 0.3826834323650898,-0.9238795325112867,0.9238795325112867,-0.3826834323650898,-0.3826834323650898,0.9238795325112867,-0.9238795325112867,0.3826834323650898,\n 0.19509032201612828,-0.5555702330196022,0.8314696123025452,-0.9807852804032304,0.9807852804032304,-0.8314696123025452,0.5555702330196022,-0.19509032201612828\n);\n/**\n * Rounds a quantized coefficient to the nearest integer, with ties going away from zero (−2.5 → −3,\n * 2.5 → 3), so positive and negative values round the same way. `Math.round` alone sends −2.5 to −2.\n */\nexport function roundJpegCoefficient(value: number): number {\n return value<0 ? -Math.round(-value) : Math.round(value);\n}\n\n/** Internal baseline JPEG settings: 8-bit YCbCr 4:4:4, one explicit constant quantization step, and uniform Huffman tables written for this project. */\nexport interface ExportJpegInput { width: number; height: number; samples: readonly number[]; quantizationStep: number; exif: Uint8Array; xmp: Uint8Array }\n/** Encodes a baseline JPEG with a directly computed DCT. Uses no third-party encoder source, default quantization tables or Huffman tables. */\nexport function encodeExportJpeg(input: ExportJpegInput): Uint8Array {\n const { width, height, samples, quantizationStep: q } = input;\n if (![width,height,q].every(Number.isSafeInteger) || width < 1 || height < 1 || width*height > 4096 ||\n q < 1 || q > 255 || samples.length !== width*height*3 || Array.from(samples).some((v) => !Number.isInteger(v) || v < 0 || v > 255)) {\n throw new InvalidConfigurationError(\"Unsupported baseline JPEG input.\");\n }\n const encoder=createExportJpegEncoder({...input,maximumOutputBytes:1_000_000});\n for(let by=0;by<height;by+=8)for(let bx=0;bx<width;bx+=8){\n const block:number[]=[];\n for(let y=0;y<8;y++)for(let x=0;x<8;x++){\n const p=(Math.min(by+y,height-1)*width+Math.min(bx+x,width-1))*3;\n block.push(samples[p]!,samples[p+1]!,samples[p+2]!);\n }\n encoder.writeRgbBlock(block);\n }\n return encoder.finish();\n}\n/**\n * Largest byte budget the internal writer accepts: the Print JPEG budget ceiling at the largest opt-in source\n * (256 000 000 bytes per 24 000 000 pixels at 2^27 pixels). Each caller enforces its own smaller budget.\n */\nconst EXPORT_JPEG_MAXIMUM_OUTPUT_BYTES=scaleBudgetCeiling(256_000_000,FULL_RESOLUTION_CEILING_PIXELS);\n/**\n * Internal size-limited JPEG writer. The reference export and the scalable export use exactly the same\n * DCT and entropy-coding equations.\n *\n * When `densityDotsPerInch` is supplied, it is written to the JFIF 1.02 APP0 segment as units=1 (dots\n * per inch) with equal X and Y density. JFIF density fields are 16-bit unsigned, so it must be an integer\n * in 1..65535; callers round any fractional density and store the exact value in EXIF. When omitted,\n * APP0 keeps units=0 with a 1:1 pixel aspect ratio and states no physical size.\n */\nexport function createExportJpegEncoder(input: Omit<ExportJpegInput,\"samples\"> & {maximumOutputBytes:number;icc?:Uint8Array;densityDotsPerInch?:number}): {\n writeRgbBlock(samples:readonly number[]):void; finish():Uint8Array; dispose():void;\n} {\n const {width,height,quantizationStep:q}=input;\n if(![width,height,q,input.maximumOutputBytes].every(Number.isSafeInteger)||width<1||height<1||width>65535||height>65535||q<1||q>255||input.maximumOutputBytes<1||input.maximumOutputBytes>EXPORT_JPEG_MAXIMUM_OUTPUT_BYTES)\n throw new InvalidConfigurationError(\"Invalid bounded JPEG encoding plan.\");\n const density=input.densityDotsPerInch;\n if(density!==undefined&&(!Number.isSafeInteger(density)||density<1||density>65535))\n throw new InvalidConfigurationError(\"JFIF density requires an integer from 1 to 65535 dots per inch.\");\n // Growable output. Capacity starts at min(budget, 64 KiB) and doubles, but never beyond the budget. The budget\n // check is unchanged (offset + n > maximumOutputBytes fails), so the output bytes and failures are the same as\n // with a buffer allocated at full budget up front. An old buffer is zeroed after its bytes are copied over.\n const budget=input.maximumOutputBytes;\n let storage=new Uint8Array(Math.min(budget,65_536)),offset=0,disposed=false,blocks=0;\n const reserve=(count:number):void=>{\n if(disposed||offset+count>budget)throw new InvalidConfigurationError(\"JPEG output exceeds admitted byte budget or is disposed.\");\n if(offset+count<=storage.length)return;\n const grown=new Uint8Array(Math.min(budget,Math.max(storage.length*2,offset+count)));\n grown.set(storage.subarray(0,offset));storage.fill(0,0,offset);storage=grown;\n };\n const push=(...values:number[]):void=>{reserve(values.length);storage.set(values,offset);offset+=values.length;};\n // Fast path for one entropy-coded byte: the same budget/disposal check and byte order as push(), without an array per byte.\n const pushByte=(value:number):void=>{if(disposed||offset>=storage.length)reserve(1);storage[offset++]=value;};\n push(255,216);\n const marker = (id: number, payload: readonly number[]): void => {\n if (payload.length > 65533) throw new InvalidConfigurationError(\"JPEG metadata segment exceeds the standard APP limit.\");\n push(255,id,(payload.length+2)>>8,(payload.length+2)&255,...payload);\n };\n // JFIF 1.02 APP0: identifier, version 1.02, units (0 aspect ratio only, 1 dots per inch), Xdensity, Ydensity, no thumbnail.\n marker(224,density===undefined ? [74,70,73,70,0,1,2,0,0,1,0,1,0,0] : [74,70,73,70,0,1,2,1,density>>8,density&255,density>>8,density&255,0,0]);\n marker(225,[69,120,105,102,0,0,...input.exif]);\n marker(225,[...new TextEncoder().encode(\"http://ns.adobe.com/xap/1.0/\\0\"),...input.xmp]);\n if(input.icc){\n if(input.icc.length>65519)throw new InvalidConfigurationError(\"ICC profile exceeds the single-segment encoding envelope.\");\n marker(226,[...new TextEncoder().encode(\"ICC_PROFILE\\0\"),1,1,...input.icc]);\n }\n marker(219,[0,...Array<number>(64).fill(q)]);\n marker(192,[8,height>>8,height&255,width>>8,width&255,3,1,17,0,2,17,0,3,17,0]);\n // DC categories 0..11 use 4-bit codes; AC EOB/ZRL and all baseline run/category pairs use 8-bit codes.\n // Incomplete canonical Huffman trees reserve the all-ones code, so JPEG bit padding (1-bits) can never be read as a symbol.\n const dc = Array.from({length:12},(_,i) => i), ac = [0,240];\n for (let run=0;run<16;run++) for (let size=1;size<=10;size++) ac.push(run*16+size);\n marker(196,[0,...Array.from({length:16},(_,i) => i===3 ? 12 : 0),...dc,\n 16,...Array.from({length:16},(_,i) => i===7 ? ac.length : 0),...ac]);\n marker(218,[3,1,0,2,0,3,0,0,63,0]);\n let accumulator=0, bits=0;\n // Appends the low `count` bits (count <= 16) most-significant first, emitting each completed byte with 0xFF stuffing.\n const emit = (value: number, count: number): void => {\n accumulator=(accumulator<<count)|(value&((1<<count)-1)); bits+=count;\n while (bits>=8) { bits-=8; const byte=(accumulator>>>bits)&255; pushByte(byte); if (byte===255) pushByte(0); }\n accumulator&=(1<<bits)-1;\n };\n const amplitude = (value: number, max: number): number => {\n const size=value===0 ? 0 : Math.floor(Math.log2(Math.abs(value)))+1;\n if (size>max) throw new InvalidConfigurationError(\"JPEG coefficient exceeds baseline entropy range.\");\n return size;\n };\n const coefficient = (value: number, size: number): void => { if (size) emit(value>=0 ? value : value+(1<<size)-1,size); };\n const zigzag=new Int32Array(64);\n for (let diagonal=0,i=0;diagonal<=14;diagonal++) {\n const points: number[] = [];\n for (let y=0;y<8;y++) { const x=diagonal-y; if (x>=0 && x<8) points.push(y*8+x); }\n for (const point of diagonal%2===0 ? points.reverse() : points) zigzag[i++]=point;\n }\n // Huffman symbol index of each AC (run, size) pair; equals ac.indexOf(symbol) for every emitted symbol.\n const acIndex=new Int16Array(256).fill(-1);\n for (let i=ac.length-1;i>=0;i--) acIndex[ac[i]!]=i;\n/**\n * The 8×8 DCT, computed directly, with orthonormal DC factors and one chosen quantization step.\n *\n * This is a deliberately simple 4:4:4 reference encoder. Lossy quantization means exact RGB pixels are\n * not preserved. Decoding the JPEG and comparing is an interoperability check, not an exact scientific\n * check of pixel values.\n *\n * Each coefficient is the direct 64-term sum Σ_y Σ_x (f(x,y)·C(u,x))·C(v,y), summed over y, then x.\n * The row products f(x,y)·C(u,x) are computed once per u and reused for all eight v. This reuses the\n * identical IEEE-754 products and keeps the exact order of multiplication and summation. A factored\n * row/column DCT would reorder the sum, so it is deliberately not used.\n *\n * C(u,x) comes from the fixed table `JPEG_DCT_COSINES` (correctly rounded constants), not `Math.cos`,\n * so the coefficients do not depend on the JavaScript engine's maths library. Each quantized coefficient\n * is rounded half away from zero (`roundJpegCoefficient`).\n */\n const cosine=JPEG_DCT_COSINES;\n const previous=[0,0,0];\n const planes=[new Float64Array(64),new Float64Array(64),new Float64Array(64)];\n const transformed=new Float64Array(64);\n const blueScale=2*(1-.114), redScale=2*(1-.299);\n return {\n writeRgbBlock(samples:readonly number[]):void {\n let valid=!disposed&&blocks<Math.ceil(width/8)*Math.ceil(height/8)&&samples.length===192;\n for(let i=0;valid&&i<192;i++){const v=samples[i]!;valid=Number.isInteger(v)&&v>=0&&v<=255;}\n if(!valid)throw new InvalidConfigurationError(\"JPEG requires complete bounded RGB coding blocks.\");\n const [luma,blueDifference,redDifference]=planes as [Float64Array,Float64Array,Float64Array];\n for (let i=0;i<64;i++) {\n // JPEG pads only partial 8x8 blocks (MCUs, minimum coded units). The declared image and crop size never change.\n const p=i*3;\n const red=samples[p]!, green=samples[p+1]!, blue=samples[p+2]!, luminance=.299*red+.587*green+.114*blue;\n luma[i]=luminance-128; blueDifference[i]=(blue-luminance)/blueScale; redDifference[i]=(red-luminance)/redScale;\n }\n for (let channel=0;channel<3;channel++) {\n const block=planes[channel]!;\n for (let u=0;u<8;u++) {\n const uOffset=u*8;\n const uFactor=u===0 ? Math.SQRT1_2 : 1;\n // The eight v sums in one pass over (y, x): each sum still adds the same products f(x,y)·C(u,x)·C(v,y) in the same\n // order (y, then x), and each row product is the same IEEE product, formed once per (x, y) instead of stored.\n let s0=0, s1=0, s2=0, s3=0, s4=0, s5=0, s6=0, s7=0;\n for (let y=0;y<8;y++) {\n const c0=cosine[y]!, c1=cosine[8+y]!, c2=cosine[16+y]!, c3=cosine[24+y]!, c4=cosine[32+y]!, c5=cosine[40+y]!, c6=cosine[48+y]!, c7=cosine[56+y]!;\n for (let x=0;x<8;x++) {\n const r=block[y*8+x]!*cosine[uOffset+x]!;\n s0+=r*c0; s1+=r*c1; s2+=r*c2; s3+=r*c3; s4+=r*c4; s5+=r*c5; s6+=r*c6; s7+=r*c7;\n }\n }\n // Scaled as before, left to right: sum·0.25·(u factor)·(v factor)/q.\n transformed[u]=roundJpegCoefficient(s0*.25*uFactor*Math.SQRT1_2/q); transformed[8+u]=roundJpegCoefficient(s1*.25*uFactor*1/q);\n transformed[16+u]=roundJpegCoefficient(s2*.25*uFactor*1/q); transformed[24+u]=roundJpegCoefficient(s3*.25*uFactor*1/q);\n transformed[32+u]=roundJpegCoefficient(s4*.25*uFactor*1/q); transformed[40+u]=roundJpegCoefficient(s5*.25*uFactor*1/q);\n transformed[48+u]=roundJpegCoefficient(s6*.25*uFactor*1/q); transformed[56+u]=roundJpegCoefficient(s7*.25*uFactor*1/q);\n }\n const difference=transformed[0]!-previous[channel]!, size=amplitude(difference,11); emit(size,4); coefficient(difference,size); previous[channel]=transformed[0]!;\n let zeroes=0;\n for (let i=1;i<64;i++) {\n const value=transformed[zigzag[i]!]!;\n if (value===0) { zeroes++; continue; }\n while (zeroes>=16) { emit(1,8); zeroes-=16; }\n const length=amplitude(value,10), symbol=zeroes*16+length; emit(acIndex[symbol]!,8); coefficient(value,length); zeroes=0;\n }\n if (zeroes) emit(0,8);\n }\n blocks++;\n },\n finish():Uint8Array {\n if(disposed||blocks!==Math.ceil(width/8)*Math.ceil(height/8))throw new InvalidConfigurationError(\"JPEG cannot finish incomplete or disposed encoding.\");\n if(bits)emit((1<<(8-bits))-1,8-bits);\n // Only the written prefix can hold data; zero it after the copy instead of filling the whole capacity.\n push(255,217);const output=storage.slice(0,offset);storage.fill(0,0,offset);storage=new Uint8Array(0);disposed=true;return output;\n },\n dispose():void {storage.fill(0,0,offset);storage=new Uint8Array(0);disposed=true;}\n };\n}\n"]}
|
package/dist/core/version.d.ts
CHANGED
package/dist/core/version.js
CHANGED
package/dist/core/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/core/version.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,OAAgB,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Version of the engine release. Since 1.0.1 it equals the npm package version.\n *\n * New captures and plans record this version as their creator. Archived records keep the\n * version they were made with. Proof-of-concept (POC), schema and model contracts have their\n * own versions. Release checks confirm it matches package.json and the packed package.\n * @see docs/RELEASE_1_0_1.md\n */\nexport const ENGINE_API_VERSION = \"2.8.
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/core/version.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,OAAgB,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Version of the engine release. Since 1.0.1 it equals the npm package version.\n *\n * New captures and plans record this version as their creator. Archived records keep the\n * version they were made with. Proof-of-concept (POC), schema and model contracts have their\n * own versions. Release checks confirm it matches package.json and the packed package.\n * @see docs/RELEASE_1_0_1.md\n */\nexport const ENGINE_API_VERSION = \"2.8.1\" as const;\n"]}
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
import { InvalidConfigurationError } from "../core/configuration-error.js";
|
|
43
43
|
import { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from "../core/internal-radiance-evaluator.js";
|
|
44
44
|
import { calculateIrradianceConvolution } from "../optics/irradiance-convolution.js";
|
|
45
|
-
import {
|
|
45
|
+
import { siteDiffractionKernel } from "../optics/site-diffraction-kernel.js";
|
|
46
46
|
/** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */
|
|
47
47
|
const BAND_ROWS = 32;
|
|
48
48
|
const CACHED_BANDS = 4;
|
|
@@ -71,15 +71,8 @@ export function createDiffractedPlanarProvider(input) {
|
|
|
71
71
|
if (!(lx0 < lx1 && ly0 < ly1))
|
|
72
72
|
throw new InvalidConfigurationError("Diffraction window must overlap the native raster.");
|
|
73
73
|
const NW = lx1 - lx0;
|
|
74
|
-
// One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0).
|
|
75
|
-
const kernels = wavelengthsNm.map((wavelengthNm) =>
|
|
76
|
-
const k = resolveLensPsfConvolutionKernels({ schemaVersion: "0.1.0", psf: input.psf, spectralWeights: [{ wavelengthNm, weight: 1 }],
|
|
77
|
-
grid: { width: 1, height: 1, sitePitchMicrometers: { x: pitch, y: pitch }, opticalAxisSite: { x: 0.5, y: 0.5 } }, patchWidth: 1, patchHeight: 1,
|
|
78
|
-
kernelRadius: R }).value;
|
|
79
|
-
if (!k.exactSiteSampling || k.kernelRadius !== R)
|
|
80
|
-
throw new InvalidConfigurationError("Diffraction kernels must sample the site pitch exactly.");
|
|
81
|
-
return k.kernels;
|
|
82
|
-
});
|
|
74
|
+
// One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0); kept across calls.
|
|
75
|
+
const kernels = wavelengthsNm.map((wavelengthNm) => siteDiffractionKernel(input.psf, wavelengthNm, pitch, R, "Diffraction kernels must sample the site pitch exactly."));
|
|
83
76
|
const gridWidth = NW + 2 * R;
|
|
84
77
|
const now = () => globalThis.performance?.now() ?? Date.now();
|
|
85
78
|
const bands = new Map();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diffraction-provider.js","sourceRoot":"","sources":["../../src/facade/diffraction-provider.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gCAAgC,EAAE,kCAAkC,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAE9J,OAAO,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AACrF,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAIjF,gHAAgH;AAChH,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,uBAAuB,GAAG,IAAI,CAAC;AA+BrC,2HAA2H;AAC3H,MAAM,UAAU,8BAA8B,CAAC,KAAoC;IACjF,MAAM,EAAE,IAAI,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,GAAG,KAAK,CAAC;IACxF,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,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C;gBACpJ,MAAM,EAAE,GAAG,GAAG,GAAG,EAAE,EAAE,IAAI,GAAG,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,GAAG,IAAI,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC;gBAClF,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,CAAE,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,GAAG,CAAE,CAAC;YACrG,CAAC;SACF,CAAC,CAAC;IACL,CAAC;IACD,OAAO;QACL,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,iBAAiB,EAAE,IAAI,CAAC,iBAAiB,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU;QAC7F,gBAAgB;QAChB,wBAAwB;YACtB,MAAM,IAAI,yBAAyB,CAAC,mEAAmE,CAAC,CAAC;QAC3G,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Fast execution of `simulateCapture`'s `lens.diffraction` (2.1): an object-space convolution in the scene\n * provider, instead of one scene query per PSF tap in the environment PSF quadrature.\n *\n * The environment quadrature computes, at each site centre q and spectral node λ,\n * E(q, λ) = Σ_k K_λ(k)·T·L(s_k(q), λ),\n * where s_k(q) is the tap's source point (`sensorPsfSourcePoint`), L the scene radiance at the plane point\n * that source point sees, and T the radiance-to-irradiance factor. For the facade's planar scene seen\n * through the ideal rectilinear projection with a still camera and no lens field mapping, field throughput or\n * pupil rays:\n * - T is the same at every sensor point (paraxial π/(4·N_w²), no cos⁴ term), and\n * - with the kernel sampled on the site pitch, every source point is the centre of another site, so the plane\n * points form one regular lattice: u = (i + ½ − W/2)·2/w, v = −(j + ½ − H/2)·2/w (frame units, native\n * site (i, j), W×H native sites, w output width).\n * So E(q, λ) = T·B(q, λ) with B = K_λ ⊛ L sampled on that lattice: the same sum, in a different floating-point\n * order. B is computed once per spectral node with the engine's isoplanatic convolution\n * (`calculateIrradianceConvolution`, kernels from `resolveLensPsfConvolutionKernels`, exact site sampling) over a\n * grid that holds every source (the native raster plus the kernel radius on each side), in row bands. The\n * provider then answers each site-centre query with B instead of L, and the environment request declares no\n * PSF. Incoherent imaging is a linear superposition of intensity PSFs, so convolving radiance on the object\n * plane and convolving irradiance on the image plane agree for a planar object and a space-invariant PSF\n * (MIT OpenCourseWare 2.71, lecture 22, free; also see: Goodman, Introduction to Fourier Optics, 4th ed., §7.1).\n *\n * With an anti-aliasing point-splitting filter (2.1, `sensor.antiAliasing`) the environment queries the PSF taps\n * around each pre-filter source point q − a (a = a split offset) instead of around q. Those taps lie on the site\n * lattice shifted by a, so the same argument holds on each shifted lattice: B is computed once per distinct\n * fractional shift (offsets that differ by whole sites share one lattice; the centred four-spot filter with a\n * one-site separation needs a single half-site-shifted lattice) over the native raster widened by the largest\n * offset, and the environment's spatial quadrature still forms the weighted split sum.\n *\n * Region renders (2.6, `window`): only the lattice rows and columns that the region's sites can query (the window\n * plus the largest offset on each side) are convolved, over a grid that adds the kernel radius on each side. Every\n * output value is the same gather as in the whole render: the grid always holds every tap of every value it keeps\n * (real scene radiance out to the kernel radius, never a truncated edge), the single kernel patch does not depend on\n * the grid's origin, and `convolveIrradianceRows` sums each value in a fixed tap order (v outer, u inner). Narrowing\n * the grid therefore removes only values that no query reads, and the kept values are bit-identical.\n *\n * A query that does not land on one of the lattices (within 1e-6 site) is refused rather than approximated: the\n * facade uses this path only when the lattice argument above holds. A query outside the window is refused too.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from \"../core/internal-radiance-evaluator.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport { calculateIrradianceConvolution } from \"../optics/irradiance-convolution.js\";\nimport { resolveLensPsfConvolutionKernels } from \"../optics/lens-psf-kernels.js\";\nimport type { ResolveLensSampledPsfInput } from \"../optics/lens-psf-profile.js\";\nimport type { PlanarSceneRadianceProvider } from \"./scene-radiance.js\";\n\n/** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */\nconst BAND_ROWS = 32;\nconst CACHED_BANDS = 4;\nconst LATTICE_TOLERANCE_SITES = 1e-6;\n\nexport interface DiffractedPlanarProviderInput {\n base: PlanarSceneRadianceProvider;\n /** The optical state of the sampled PSF, as for `resolveLensSampledPsf`, without field point and wavelength. */\n psf: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /** Spectral nodes the environment queries (the profile's wavelength nodes). */\n wavelengthsNm: readonly number[];\n kernelRadius: number;\n nativeWidth: number;\n nativeHeight: number;\n /** Output (active) width in sites: frame units are 2/outputWidth per site. */\n outputWidth: number;\n sitePitchMicrometers: number;\n /** Planar geometry of the base provider, to map query directions to plane points exactly as it does. */\n distanceM: number;\n metresPerFrameUnit: number;\n /**\n * Offsets of the query points from the site centres, in sites (+x right, +y down): the anti-aliasing split\n * offsets with their sign reversed (the environment queries q − a). Default: one zero offset.\n */\n queryOffsetsSites?: readonly { x: number; y: number }[];\n /**\n * Region renders (2.6): the native sites that will be queried (x, y, width, height in the native raster). Only the\n * lattice they can reach is convolved; values are bit-identical to the whole render's. Default: the whole raster.\n */\n window?: { x: number; y: number; width: number; height: number };\n /** Called with the duration in ms of each band convolution (diagnostics only; never changes values). */\n onConvolution?: (milliseconds: number) => void;\n}\n\n/** Internal (not exported from the package): the base provider with diffraction applied as an object-space convolution. */\nexport function createDiffractedPlanarProvider(input: DiffractedPlanarProviderInput): PlanarSceneRadianceProvider {\n const { base, wavelengthsNm, nativeWidth: W, nativeHeight: H, kernelRadius: R } = input;\n const g = 2 / input.outputWidth, pitch = input.sitePitchMicrometers;\n const index = new Map(wavelengthsNm.map((nm, i) => [nm, i]));\n // One lattice per distinct fractional query offset; M extra sites per side hold the offset queries.\n const offsets = input.queryOffsetsSites ?? [{ x: 0, y: 0 }];\n const fraction = (value: number): number => { const f = value - Math.floor(value); return f > 1 - LATTICE_TOLERANCE_SITES ? 0 : f < LATTICE_TOLERANCE_SITES ? 0 : f; };\n const shifts: { x: number; y: number }[] = [];\n for (const o of offsets) {\n const f = { x: fraction(o.x), y: fraction(o.y) };\n if (!shifts.some((s) => Math.abs(s.x - f.x) <= LATTICE_TOLERANCE_SITES && Math.abs(s.y - f.y) <= LATTICE_TOLERANCE_SITES)) shifts.push(f);\n }\n const M = Math.max(0, ...offsets.map((o) => Math.ceil(Math.max(Math.abs(o.x), Math.abs(o.y)) - LATTICE_TOLERANCE_SITES)));\n const LW = W + 2 * M, LH = H + 2 * M;\n // Lattice window (indices i + M, j + M): the sites the region queries plus the largest offset on each side, clipped\n // to the lattice. A site i queries i + floor(offset), and floor(offset) lies in [-M, M].\n const win = input.window ?? { x: 0, y: 0, width: W, height: H };\n const lx0 = Math.max(0, win.x), lx1 = Math.min(LW, win.x + win.width + 2 * M);\n const ly0 = Math.max(0, win.y), ly1 = Math.min(LH, win.y + win.height + 2 * M);\n if (!(lx0 < lx1 && ly0 < ly1)) throw new InvalidConfigurationError(\"Diffraction window must overlap the native raster.\");\n const NW = lx1 - lx0;\n // One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0).\n const kernels = wavelengthsNm.map((wavelengthNm) => {\n const k = resolveLensPsfConvolutionKernels({ schemaVersion: \"0.1.0\", psf: input.psf, spectralWeights: [{ wavelengthNm, weight: 1 }],\n grid: { width: 1, height: 1, sitePitchMicrometers: { x: pitch, y: pitch }, opticalAxisSite: { x: 0.5, y: 0.5 } }, patchWidth: 1, patchHeight: 1,\n kernelRadius: R }).value;\n if (!k.exactSiteSampling || k.kernelRadius !== R) throw new InvalidConfigurationError(\"Diffraction kernels must sample the site pitch exactly.\");\n return k.kernels;\n });\n const gridWidth = NW + 2 * R;\n const now = (): number => globalThis.performance?.now() ?? Date.now();\n const bands = new Map<number, Float64Array[][]>();\n function band(b: number): Float64Array[][] {\n const cached = bands.get(b);\n if (cached) { bands.delete(b); bands.set(b, cached); return cached; }\n const started = input.onConvolution ? now() : 0;\n const y0 = ly0 + b * BAND_ROWS, rows = Math.min(BAND_ROWS, ly1 - y0), gridHeight = rows + 2 * R;\n const values = shifts.map((shift) => wavelengthsNm.map((nm, w) => {\n const samples = new Float64Array(gridWidth * gridHeight);\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = shift.y === 0 ? -(y0 + gy - R - M + 0.5 - H / 2) * g : -(y0 + gy - R - M + 0.5 + shift.y - H / 2) * g;\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) samples[gy * gridWidth + gx] = base.radianceAt(shift.x === 0 ? (x - R - M + 0.5 - W / 2) * g : (x - R - M + 0.5 + shift.x - W / 2) * g, v, nm);\n }\n const blurred = calculateIrradianceConvolution({ schemaVersion: \"0.1.0\", width: gridWidth, height: gridHeight, samples, kernelRadius: R,\n patchWidth: gridWidth, patchHeight: gridHeight, kernels: kernels[w]!, boundary: \"zero-outside-grid\" }).values;\n const out = new Float64Array(NW * rows);\n for (let y = 0; y < rows; y++) out.set(blurred.subarray((y + R) * gridWidth + R, (y + R) * gridWidth + R + NW), y * NW);\n return out;\n }));\n bands.set(b, values);\n if (bands.size > CACHED_BANDS) bands.delete(bands.keys().next().value!);\n if (input.onConvolution) input.onConvolution(now() - started);\n return values;\n }\n function blurredAt(u: number, v: number, nm: number): number {\n const w = index.get(nm), fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n if (w !== undefined) for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) break;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n }\n const scale = input.metresPerFrameUnit, distance = input.distanceM, baseEvaluate = base.evaluateRadiance;\n const evaluateRadiance = (request: Readonly<SceneRadianceEvaluationRequest>): SceneRadianceEvaluationResult => {\n const result = baseEvaluate.call(base, request), o = (request.target as { outgoingDirectionUnitVector: { x: number; y: number; z: number } }).outgoingDirectionUnitVector;\n const t = distance / -o.z;\n return { ...result, spectralRadianceWattsPerSquareMeterSteradianNanometer: blurredAt(-o.x * t / scale, -o.y * t / scale, request.wavelengthNanometers) };\n };\n // 2.6: the result is the base result with only its radiance replaced (same keys and records), so an engine-built base\n // evaluator keeps its mark (see core/internal-radiance-evaluator.ts).\n if (isInternalSceneRadianceEvaluator(baseEvaluate)) {\n markInternalSceneRadianceEvaluator(evaluateRadiance);\n // #394: its radiance is the convolved value at one lattice site (shift s, lattice column li, row lj) per wavelength, so\n // the lean executor may read it by that key: the same plane point, lattice choice and band value as evaluateRadiance.\n registerInternalRadianceAccess(evaluateRadiance, {\n tabulated: false,\n keyOfDirection(o): number | undefined {\n if (!(-o.z > 0)) return undefined;\n const t = distance / -o.z, u = -o.x * t / scale, v = -o.y * t / scale, fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) return undefined;\n return (s * LH + lj) * LW + li;\n }\n return undefined;\n },\n radianceOfKey(key, nm): number {\n const w = index.get(nm);\n if (w === undefined) throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n const li = key % LW, rest = (key - li) / LW, lj = rest % LH, s = (rest - lj) / LH;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n });\n }\n return {\n sceneId: base.sceneId, providerProfileId: base.providerProfileId, radianceAt: base.radianceAt,\n evaluateRadiance,\n evaluateApertureRadiance(): SceneRadianceEvaluationResult {\n throw new InvalidConfigurationError(\"Diffraction by object-space convolution does not take pupil rays.\");\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"diffraction-provider.js","sourceRoot":"","sources":["../../src/facade/diffraction-provider.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gCAAgC,EAAE,kCAAkC,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAE9J,OAAO,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AACrF,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAI7E,gHAAgH;AAChH,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,uBAAuB,GAAG,IAAI,CAAC;AA+BrC,2HAA2H;AAC3H,MAAM,UAAU,8BAA8B,CAAC,KAAoC;IACjF,MAAM,EAAE,IAAI,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,GAAG,KAAK,CAAC;IACxF,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,WAAW,EAAE,KAAK,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AAE,IAAI,CAAC,iBAAiB,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU;QAC7F,gBAAgB;QAChB,wBAAwB;YACtB,MAAM,IAAI,yBAAyB,CAAC,mEAAmE,CAAC,CAAC;QAC3G,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Fast execution of `simulateCapture`'s `lens.diffraction` (2.1): an object-space convolution in the scene\n * provider, instead of one scene query per PSF tap in the environment PSF quadrature.\n *\n * The environment quadrature computes, at each site centre q and spectral node λ,\n * E(q, λ) = Σ_k K_λ(k)·T·L(s_k(q), λ),\n * where s_k(q) is the tap's source point (`sensorPsfSourcePoint`), L the scene radiance at the plane point\n * that source point sees, and T the radiance-to-irradiance factor. For the facade's planar scene seen\n * through the ideal rectilinear projection with a still camera and no lens field mapping, field throughput or\n * pupil rays:\n * - T is the same at every sensor point (paraxial π/(4·N_w²), no cos⁴ term), and\n * - with the kernel sampled on the site pitch, every source point is the centre of another site, so the plane\n * points form one regular lattice: u = (i + ½ − W/2)·2/w, v = −(j + ½ − H/2)·2/w (frame units, native\n * site (i, j), W×H native sites, w output width).\n * So E(q, λ) = T·B(q, λ) with B = K_λ ⊛ L sampled on that lattice: the same sum, in a different floating-point\n * order. B is computed once per spectral node with the engine's isoplanatic convolution\n * (`calculateIrradianceConvolution`, kernels from `resolveLensPsfConvolutionKernels`, exact site sampling) over a\n * grid that holds every source (the native raster plus the kernel radius on each side), in row bands. The\n * provider then answers each site-centre query with B instead of L, and the environment request declares no\n * PSF. Incoherent imaging is a linear superposition of intensity PSFs, so convolving radiance on the object\n * plane and convolving irradiance on the image plane agree for a planar object and a space-invariant PSF\n * (MIT OpenCourseWare 2.71, lecture 22, free; also see: Goodman, Introduction to Fourier Optics, 4th ed., §7.1).\n *\n * With an anti-aliasing point-splitting filter (2.1, `sensor.antiAliasing`) the environment queries the PSF taps\n * around each pre-filter source point q − a (a = a split offset) instead of around q. Those taps lie on the site\n * lattice shifted by a, so the same argument holds on each shifted lattice: B is computed once per distinct\n * fractional shift (offsets that differ by whole sites share one lattice; the centred four-spot filter with a\n * one-site separation needs a single half-site-shifted lattice) over the native raster widened by the largest\n * offset, and the environment's spatial quadrature still forms the weighted split sum.\n *\n * Region renders (2.6, `window`): only the lattice rows and columns that the region's sites can query (the window\n * plus the largest offset on each side) are convolved, over a grid that adds the kernel radius on each side. Every\n * output value is the same gather as in the whole render: the grid always holds every tap of every value it keeps\n * (real scene radiance out to the kernel radius, never a truncated edge), the single kernel patch does not depend on\n * the grid's origin, and `convolveIrradianceRows` sums each value in a fixed tap order (v outer, u inner). Narrowing\n * the grid therefore removes only values that no query reads, and the kept values are bit-identical.\n *\n * A query that does not land on one of the lattices (within 1e-6 site) is refused rather than approximated: the\n * facade uses this path only when the lattice argument above holds. A query outside the window is refused too.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from \"../core/internal-radiance-evaluator.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport { calculateIrradianceConvolution } from \"../optics/irradiance-convolution.js\";\nimport { siteDiffractionKernel } from \"../optics/site-diffraction-kernel.js\";\nimport type { ResolveLensSampledPsfInput } from \"../optics/lens-psf-profile.js\";\nimport type { PlanarSceneRadianceProvider } from \"./scene-radiance.js\";\n\n/** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */\nconst BAND_ROWS = 32;\nconst CACHED_BANDS = 4;\nconst LATTICE_TOLERANCE_SITES = 1e-6;\n\nexport interface DiffractedPlanarProviderInput {\n base: PlanarSceneRadianceProvider;\n /** The optical state of the sampled PSF, as for `resolveLensSampledPsf`, without field point and wavelength. */\n psf: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /** Spectral nodes the environment queries (the profile's wavelength nodes). */\n wavelengthsNm: readonly number[];\n kernelRadius: number;\n nativeWidth: number;\n nativeHeight: number;\n /** Output (active) width in sites: frame units are 2/outputWidth per site. */\n outputWidth: number;\n sitePitchMicrometers: number;\n /** Planar geometry of the base provider, to map query directions to plane points exactly as it does. */\n distanceM: number;\n metresPerFrameUnit: number;\n /**\n * Offsets of the query points from the site centres, in sites (+x right, +y down): the anti-aliasing split\n * offsets with their sign reversed (the environment queries q − a). Default: one zero offset.\n */\n queryOffsetsSites?: readonly { x: number; y: number }[];\n /**\n * Region renders (2.6): the native sites that will be queried (x, y, width, height in the native raster). Only the\n * lattice they can reach is convolved; values are bit-identical to the whole render's. Default: the whole raster.\n */\n window?: { x: number; y: number; width: number; height: number };\n /** Called with the duration in ms of each band convolution (diagnostics only; never changes values). */\n onConvolution?: (milliseconds: number) => void;\n}\n\n/** Internal (not exported from the package): the base provider with diffraction applied as an object-space convolution. */\nexport function createDiffractedPlanarProvider(input: DiffractedPlanarProviderInput): PlanarSceneRadianceProvider {\n const { base, wavelengthsNm, nativeWidth: W, nativeHeight: H, kernelRadius: R } = input;\n const g = 2 / input.outputWidth, pitch = input.sitePitchMicrometers;\n const index = new Map(wavelengthsNm.map((nm, i) => [nm, i]));\n // One lattice per distinct fractional query offset; M extra sites per side hold the offset queries.\n const offsets = input.queryOffsetsSites ?? [{ x: 0, y: 0 }];\n const fraction = (value: number): number => { const f = value - Math.floor(value); return f > 1 - LATTICE_TOLERANCE_SITES ? 0 : f < LATTICE_TOLERANCE_SITES ? 0 : f; };\n const shifts: { x: number; y: number }[] = [];\n for (const o of offsets) {\n const f = { x: fraction(o.x), y: fraction(o.y) };\n if (!shifts.some((s) => Math.abs(s.x - f.x) <= LATTICE_TOLERANCE_SITES && Math.abs(s.y - f.y) <= LATTICE_TOLERANCE_SITES)) shifts.push(f);\n }\n const M = Math.max(0, ...offsets.map((o) => Math.ceil(Math.max(Math.abs(o.x), Math.abs(o.y)) - LATTICE_TOLERANCE_SITES)));\n const LW = W + 2 * M, LH = H + 2 * M;\n // Lattice window (indices i + M, j + M): the sites the region queries plus the largest offset on each side, clipped\n // to the lattice. A site i queries i + floor(offset), and floor(offset) lies in [-M, M].\n const win = input.window ?? { x: 0, y: 0, width: W, height: H };\n const lx0 = Math.max(0, win.x), lx1 = Math.min(LW, win.x + win.width + 2 * M);\n const ly0 = Math.max(0, win.y), ly1 = Math.min(LH, win.y + win.height + 2 * M);\n if (!(lx0 < lx1 && ly0 < ly1)) throw new InvalidConfigurationError(\"Diffraction window must overlap the native raster.\");\n const NW = lx1 - lx0;\n // One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0); kept across calls.\n const kernels = wavelengthsNm.map((wavelengthNm) => siteDiffractionKernel(input.psf, wavelengthNm, pitch, R, \"Diffraction kernels must sample the site pitch exactly.\"));\n const gridWidth = NW + 2 * R;\n const now = (): number => globalThis.performance?.now() ?? Date.now();\n const bands = new Map<number, Float64Array[][]>();\n function band(b: number): Float64Array[][] {\n const cached = bands.get(b);\n if (cached) { bands.delete(b); bands.set(b, cached); return cached; }\n const started = input.onConvolution ? now() : 0;\n const y0 = ly0 + b * BAND_ROWS, rows = Math.min(BAND_ROWS, ly1 - y0), gridHeight = rows + 2 * R;\n const values = shifts.map((shift) => wavelengthsNm.map((nm, w) => {\n const samples = new Float64Array(gridWidth * gridHeight);\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = shift.y === 0 ? -(y0 + gy - R - M + 0.5 - H / 2) * g : -(y0 + gy - R - M + 0.5 + shift.y - H / 2) * g;\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) samples[gy * gridWidth + gx] = base.radianceAt(shift.x === 0 ? (x - R - M + 0.5 - W / 2) * g : (x - R - M + 0.5 + shift.x - W / 2) * g, v, nm);\n }\n const blurred = calculateIrradianceConvolution({ schemaVersion: \"0.1.0\", width: gridWidth, height: gridHeight, samples, kernelRadius: R,\n patchWidth: gridWidth, patchHeight: gridHeight, kernels: kernels[w]!, boundary: \"zero-outside-grid\" }).values;\n const out = new Float64Array(NW * rows);\n for (let y = 0; y < rows; y++) out.set(blurred.subarray((y + R) * gridWidth + R, (y + R) * gridWidth + R + NW), y * NW);\n return out;\n }));\n bands.set(b, values);\n if (bands.size > CACHED_BANDS) bands.delete(bands.keys().next().value!);\n if (input.onConvolution) input.onConvolution(now() - started);\n return values;\n }\n function blurredAt(u: number, v: number, nm: number): number {\n const w = index.get(nm), fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n if (w !== undefined) for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) break;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n }\n const scale = input.metresPerFrameUnit, distance = input.distanceM, baseEvaluate = base.evaluateRadiance;\n const evaluateRadiance = (request: Readonly<SceneRadianceEvaluationRequest>): SceneRadianceEvaluationResult => {\n const result = baseEvaluate.call(base, request), o = (request.target as { outgoingDirectionUnitVector: { x: number; y: number; z: number } }).outgoingDirectionUnitVector;\n const t = distance / -o.z;\n return { ...result, spectralRadianceWattsPerSquareMeterSteradianNanometer: blurredAt(-o.x * t / scale, -o.y * t / scale, request.wavelengthNanometers) };\n };\n // 2.6: the result is the base result with only its radiance replaced (same keys and records), so an engine-built base\n // evaluator keeps its mark (see core/internal-radiance-evaluator.ts).\n if (isInternalSceneRadianceEvaluator(baseEvaluate)) {\n markInternalSceneRadianceEvaluator(evaluateRadiance);\n // #394: its radiance is the convolved value at one lattice site (shift s, lattice column li, row lj) per wavelength, so\n // the lean executor may read it by that key: the same plane point, lattice choice and band value as evaluateRadiance.\n registerInternalRadianceAccess(evaluateRadiance, {\n tabulated: false,\n keyOfDirection(o): number | undefined {\n if (!(-o.z > 0)) return undefined;\n const t = distance / -o.z, u = -o.x * t / scale, v = -o.y * t / scale, fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) return undefined;\n return (s * LH + lj) * LW + li;\n }\n return undefined;\n },\n radianceOfKey(key, nm): number {\n const w = index.get(nm);\n if (w === undefined) throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n const li = key % LW, rest = (key - li) / LW, lj = rest % LH, s = (rest - lj) / LH;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n });\n }\n return {\n sceneId: base.sceneId, providerProfileId: base.providerProfileId, radianceAt: base.radianceAt,\n evaluateRadiance,\n evaluateApertureRadiance(): SceneRadianceEvaluationResult {\n throw new InvalidConfigurationError(\"Diffraction by object-space convolution does not take pupil rays.\");\n }\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolveLensPsfConvolutionKernels } from "../optics/lens-psf-kernels.js";
|
|
1
|
+
import type { resolveLensPsfConvolutionKernels } from "../optics/lens-psf-kernels.js";
|
|
2
2
|
import type { DisplayViewExpectedSignalInput } from "./display-view.js";
|
|
3
3
|
type Psf = Parameters<typeof resolveLensPsfConvolutionKernels>[0]["psf"];
|
|
4
4
|
export interface ExpectedSignalSetupInput {
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* the same way: query offsets of each site, the environment's query points, the diffraction kernels and the scene tables.
|
|
6
6
|
*/
|
|
7
7
|
import { InvalidConfigurationError } from "../core/configuration-error.js";
|
|
8
|
-
import {
|
|
8
|
+
import { siteDiffractionKernel } from "../optics/site-diffraction-kernel.js";
|
|
9
9
|
import { resolveProjectionDistanceMm } from "../motion/camera-rotation.js";
|
|
10
10
|
/** The query offsets of each site and the expected-signal input (see the module comment). */
|
|
11
11
|
export function buildExpectedSignalInput(input) {
|
|
@@ -22,11 +22,7 @@ export function buildExpectedSignalInput(input) {
|
|
|
22
22
|
kernels = { radius, perNode: wavelengths.map((wavelengthNm) => {
|
|
23
23
|
if (!diffraction.profileWavelengths.includes(wavelengthNm))
|
|
24
24
|
throw new InvalidConfigurationError(input.caller + ": a spectral node has no diffraction kernel.");
|
|
25
|
-
|
|
26
|
-
grid: { width: 1, height: 1, sitePitchMicrometers: { x: pitch, y: pitch }, opticalAxisSite: { x: 0.5, y: 0.5 } }, patchWidth: 1, patchHeight: 1, kernelRadius: radius }).value;
|
|
27
|
-
if (!k.exactSiteSampling || k.kernelRadius !== radius)
|
|
28
|
-
throw new InvalidConfigurationError(input.caller + ": diffraction kernels must sample the site pitch exactly.");
|
|
29
|
-
return Float64Array.from(k.kernels);
|
|
25
|
+
return siteDiffractionKernel(diffraction.psf, wavelengthNm, pitch, radius, input.caller + ": diffraction kernels must sample the site pitch exactly.");
|
|
30
26
|
}) };
|
|
31
27
|
}
|
|
32
28
|
// Chart presets and (2.7) caller material scenes take the material path: each material tabulated once per node.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expected-signal-setup.js","sourceRoot":"","sources":["../../src/facade/expected-signal-setup.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;GAIG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAg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,CAAC,GAAG,kBAAkB,CAAC;IAC/F,CAAC,CAAC;IACF,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,WAAW,EAAE,KAAK,CAAC,KAAK,EAAE,aAAa,EAAE,WAAW;YACrJ,oBAAoB,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE,CAAC;AAClI,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Internal (#394, not exported from the package): the input of the tabulated expected signal (`createDisplayViewExpectedSignal`)\n * for a resolved `simulateCapture` request, shared by the display view and the capture's tabulated RAW path so both build it\n * the same way: query offsets of each site, the environment's query points, the diffraction kernels and the scene tables.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { resolveLensPsfConvolutionKernels } from \"../optics/lens-psf-kernels.js\";\nimport { resolveProjectionDistanceMm } from \"../motion/camera-rotation.js\";\nimport type { DisplayViewExpectedSignalInput, DisplayViewScene } from \"./display-view.js\";\n\ntype Psf = Parameters<typeof resolveLensPsfConvolutionKernels>[0][\"psf\"];\n\nexport interface ExpectedSignalSetupInput {\n nativeWidth: number;\n nativeHeight: number;\n /** Frame output width (plane coordinates are 2 / width frame units per site). */\n width: number;\n wavelengths: readonly number[];\n /** Per CFA channel (red, green, blue): expected electrons per unit spectral radiance at each node. */\n perNode: readonly [Float64Array, Float64Array, Float64Array];\n /** Pixel-aperture nodes in sites from the site centre (`apertureNodeOffsets(boxSamples)`) and the box sample count. */\n apertureNodes: readonly { x: number; y: number }[];\n boxSamples: number;\n antiAliasing?: { components: readonly { offsetMicrometers: { x: number; y: number }; normalizedWeight: number }[] } | undefined;\n pitch: number;\n /** Object-space diffraction: the kernel radius, the PSF and its profile wavelengths. */\n diffraction?: { radius: number; psf: Psf; profileWavelengths: readonly number[] } | undefined;\n /** Material scenes: the materials (neutral reflectances, or radiance per wavelength), the material lookup and the white radiance. */\n materials?: { list: readonly ({ neutral: number } | { radiance: (nm: number) => number })[]; materialAt(u: number, v: number): number; whiteRadiance(nm: number): number } | undefined;\n radianceAt(u: number, v: number, nm: number): number;\n imagingArea: { widthMm: number; heightMm: number };\n focalLengthMm: number;\n focusDistanceM: number;\n subjectDistanceM: number;\n metresPerFrameUnit: number;\n /** Prefix of the error messages (\"simulateDisplayView\", \"simulateCapture\"). */\n caller: string;\n}\n\n/** The query offsets of each site and the expected-signal input (see the module comment). */\nexport function buildExpectedSignalInput(input: ExpectedSignalSetupInput): { offsets: { x: number; y: number; weight: number }[]; signalInput: DisplayViewExpectedSignalInput } {\n const { boxSamples, pitch, wavelengths, imagingArea, subjectDistanceM, metresPerFrameUnit } = input;\n // Query offsets of each site: pixel-aperture nodes minus anti-aliasing split offsets (sites, +x right, +y down), as the environment forms them.\n const spots = input.antiAliasing ? input.antiAliasing.components : [{ offsetMicrometers: { x: 0, y: 0 }, normalizedWeight: 1 }];\n const offsets = input.apertureNodes.flatMap((node) => spots.map((c) => ({ x: node.x - c.offsetMicrometers.x / pitch, y: node.y - c.offsetMicrometers.y / pitch,\n weight: c.normalizedWeight / (boxSamples * boxSamples) })));\n // Diffraction: the same per-node site kernels as the object-space convolution (createDiffractedPlanarProvider).\n let kernels: { radius: number; perNode: Float64Array[] } | undefined;\n const diffraction = input.diffraction;\n if (diffraction) {\n const radius = diffraction.radius;\n kernels = { radius, perNode: wavelengths.map((wavelengthNm) => {\n if (!diffraction.profileWavelengths.includes(wavelengthNm)) throw new InvalidConfigurationError(input.caller + \": a spectral node has no diffraction kernel.\");\n const k = resolveLensPsfConvolutionKernels({ schemaVersion: \"0.1.0\", psf: diffraction.psf, spectralWeights: [{ wavelengthNm, weight: 1 }],\n grid: { width: 1, height: 1, sitePitchMicrometers: { x: pitch, y: pitch }, opticalAxisSite: { x: 0.5, y: 0.5 } }, patchWidth: 1, patchHeight: 1, kernelRadius: radius }).value;\n if (!k.exactSiteSampling || k.kernelRadius !== radius) throw new InvalidConfigurationError(input.caller + \": diffraction kernels must sample the site pitch exactly.\");\n return Float64Array.from(k.kernels);\n }) };\n }\n // Chart presets and (2.7) caller material scenes take the material path: each material tabulated once per node.\n const materials = input.materials;\n const scene: DisplayViewScene = materials ? { kind: \"materials\", materialAt: materials.materialAt,\n materials: materials.list.map((m) => (\"neutral\" in m ? { neutral: m.neutral } : { radiance: Float64Array.from(wavelengths, (nm) => m.radiance(nm)) })),\n whiteRadiance: Float64Array.from(wavelengths, (nm) => materials.whiteRadiance(nm)) } :\n { kind: \"radiance\", radianceAt: input.radianceAt };\n const channelIndex = (x: number, y: number): number => ((y & 1) === 0 ? ((x & 1) === 0 ? 0 : 1) : ((x & 1) === 0 ? 1 : 2));\n // Without diffraction the environment's own query arithmetic (native-environment-lean.ts `geometry`, then the rectilinear\n // still-camera ray and the planar provider's plane point), so boundary points resolve as in the capture.\n const projectionDistance = resolveProjectionDistanceMm(input.focalLengthMm, input.focusDistanceM).projectionDistanceMm, siteWidthMm = pitch / 1000;\n const nodePhases = input.apertureNodes.flatMap((_, index) => spots.map((c) => ({ xPhase: (index % boxSamples + 0.5) / boxSamples, yPhase: (Math.floor(index / boxSamples) + 0.5) / boxSamples,\n aaX: c.offsetMicrometers.x / 1000, aaY: c.offsetMicrometers.y / 1000 })));\n const queryPoint = (x: number, y: number, o: number, out: Float64Array): void => {\n const node = nodePhases[o]!;\n const centerX = -imagingArea.widthMm / 2 + (pitch / 2 + x * pitch + 0) / 1000, centerY = -imagingArea.heightMm / 2 + (pitch / 2 + y * pitch + 0) / 1000;\n const sourceX = (centerX - siteWidthMm / 2 + node.xPhase * siteWidthMm) - node.aaX, sourceY = (centerY - siteWidthMm / 2 + node.yPhase * siteWidthMm) - node.aaY;\n const rx = projectionDistance * (sourceX / projectionDistance), ry = projectionDistance * (-sourceY / projectionDistance);\n const length = Math.hypot(rx, ry, projectionDistance), t = subjectDistanceM / (projectionDistance / length);\n out[0] = rx / length * t / metresPerFrameUnit; out[1] = ry / length * t / metresPerFrameUnit;\n };\n return { offsets, signalInput: { nativeWidth: input.nativeWidth, nativeHeight: input.nativeHeight, outputWidth: input.width, wavelengthsNm: wavelengths,\n electronsPerRadiance: input.perNode, offsets, ...(kernels ? { kernels } : { queryPoint }), scene, channelAt: channelIndex } };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"expected-signal-setup.js","sourceRoot":"","sources":["../../src/facade/expected-signal-setup.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;GAIG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAE3E,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAgC3E,6FAA6F;AAC7F,MAAM,UAAU,wBAAwB,CAAC,KAA+B;IACtE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,GAAG,KAAK,CAAC;IACpG,gJAAgJ;IAChJ,MAAM,KAAK,GAAG,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,iBAAiB,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,gBAAgB,EAAE,CAAC,EAAE,CAAC,CAAC;IAChI,MAAM,OAAO,GAAG,KAAK,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC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CAAC,CAAC,CAAC,GAAG,EAAE,GAAG,MAAM,GAAG,CAAC,GAAG,kBAAkB,CAAC;IAC/F,CAAC,CAAC;IACF,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,WAAW,EAAE,KAAK,CAAC,KAAK,EAAE,aAAa,EAAE,WAAW;YACrJ,oBAAoB,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE,CAAC;AAClI,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Internal (#394, not exported from the package): the input of the tabulated expected signal (`createDisplayViewExpectedSignal`)\n * for a resolved `simulateCapture` request, shared by the display view and the capture's tabulated RAW path so both build it\n * the same way: query offsets of each site, the environment's query points, the diffraction kernels and the scene tables.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport type { resolveLensPsfConvolutionKernels } from \"../optics/lens-psf-kernels.js\";\nimport { siteDiffractionKernel } from \"../optics/site-diffraction-kernel.js\";\nimport { resolveProjectionDistanceMm } from \"../motion/camera-rotation.js\";\nimport type { DisplayViewExpectedSignalInput, DisplayViewScene } from \"./display-view.js\";\n\ntype Psf = Parameters<typeof resolveLensPsfConvolutionKernels>[0][\"psf\"];\n\nexport interface ExpectedSignalSetupInput {\n nativeWidth: number;\n nativeHeight: number;\n /** Frame output width (plane coordinates are 2 / width frame units per site). */\n width: number;\n wavelengths: readonly number[];\n /** Per CFA channel (red, green, blue): expected electrons per unit spectral radiance at each node. */\n perNode: readonly [Float64Array, Float64Array, Float64Array];\n /** Pixel-aperture nodes in sites from the site centre (`apertureNodeOffsets(boxSamples)`) and the box sample count. */\n apertureNodes: readonly { x: number; y: number }[];\n boxSamples: number;\n antiAliasing?: { components: readonly { offsetMicrometers: { x: number; y: number }; normalizedWeight: number }[] } | undefined;\n pitch: number;\n /** Object-space diffraction: the kernel radius, the PSF and its profile wavelengths. */\n diffraction?: { radius: number; psf: Psf; profileWavelengths: readonly number[] } | undefined;\n /** Material scenes: the materials (neutral reflectances, or radiance per wavelength), the material lookup and the white radiance. */\n materials?: { list: readonly ({ neutral: number } | { radiance: (nm: number) => number })[]; materialAt(u: number, v: number): number; whiteRadiance(nm: number): number } | undefined;\n radianceAt(u: number, v: number, nm: number): number;\n imagingArea: { widthMm: number; heightMm: number };\n focalLengthMm: number;\n focusDistanceM: number;\n subjectDistanceM: number;\n metresPerFrameUnit: number;\n /** Prefix of the error messages (\"simulateDisplayView\", \"simulateCapture\"). */\n caller: string;\n}\n\n/** The query offsets of each site and the expected-signal input (see the module comment). */\nexport function buildExpectedSignalInput(input: ExpectedSignalSetupInput): { offsets: { x: number; y: number; weight: number }[]; signalInput: DisplayViewExpectedSignalInput } {\n const { boxSamples, pitch, wavelengths, imagingArea, subjectDistanceM, metresPerFrameUnit } = input;\n // Query offsets of each site: pixel-aperture nodes minus anti-aliasing split offsets (sites, +x right, +y down), as the environment forms them.\n const spots = input.antiAliasing ? input.antiAliasing.components : [{ offsetMicrometers: { x: 0, y: 0 }, normalizedWeight: 1 }];\n const offsets = input.apertureNodes.flatMap((node) => spots.map((c) => ({ x: node.x - c.offsetMicrometers.x / pitch, y: node.y - c.offsetMicrometers.y / pitch,\n weight: c.normalizedWeight / (boxSamples * boxSamples) })));\n // Diffraction: the same per-node site kernels as the object-space convolution (createDiffractedPlanarProvider).\n let kernels: { radius: number; perNode: Float64Array[] } | undefined;\n const diffraction = input.diffraction;\n if (diffraction) {\n const radius = diffraction.radius;\n kernels = { radius, perNode: wavelengths.map((wavelengthNm) => {\n if (!diffraction.profileWavelengths.includes(wavelengthNm)) throw new InvalidConfigurationError(input.caller + \": a spectral node has no diffraction kernel.\");\n return siteDiffractionKernel(diffraction.psf, wavelengthNm, pitch, radius, input.caller + \": diffraction kernels must sample the site pitch exactly.\");\n }) };\n }\n // Chart presets and (2.7) caller material scenes take the material path: each material tabulated once per node.\n const materials = input.materials;\n const scene: DisplayViewScene = materials ? { kind: \"materials\", materialAt: materials.materialAt,\n materials: materials.list.map((m) => (\"neutral\" in m ? { neutral: m.neutral } : { radiance: Float64Array.from(wavelengths, (nm) => m.radiance(nm)) })),\n whiteRadiance: Float64Array.from(wavelengths, (nm) => materials.whiteRadiance(nm)) } :\n { kind: \"radiance\", radianceAt: input.radianceAt };\n const channelIndex = (x: number, y: number): number => ((y & 1) === 0 ? ((x & 1) === 0 ? 0 : 1) : ((x & 1) === 0 ? 1 : 2));\n // Without diffraction the environment's own query arithmetic (native-environment-lean.ts `geometry`, then the rectilinear\n // still-camera ray and the planar provider's plane point), so boundary points resolve as in the capture.\n const projectionDistance = resolveProjectionDistanceMm(input.focalLengthMm, input.focusDistanceM).projectionDistanceMm, siteWidthMm = pitch / 1000;\n const nodePhases = input.apertureNodes.flatMap((_, index) => spots.map((c) => ({ xPhase: (index % boxSamples + 0.5) / boxSamples, yPhase: (Math.floor(index / boxSamples) + 0.5) / boxSamples,\n aaX: c.offsetMicrometers.x / 1000, aaY: c.offsetMicrometers.y / 1000 })));\n const queryPoint = (x: number, y: number, o: number, out: Float64Array): void => {\n const node = nodePhases[o]!;\n const centerX = -imagingArea.widthMm / 2 + (pitch / 2 + x * pitch + 0) / 1000, centerY = -imagingArea.heightMm / 2 + (pitch / 2 + y * pitch + 0) / 1000;\n const sourceX = (centerX - siteWidthMm / 2 + node.xPhase * siteWidthMm) - node.aaX, sourceY = (centerY - siteWidthMm / 2 + node.yPhase * siteWidthMm) - node.aaY;\n const rx = projectionDistance * (sourceX / projectionDistance), ry = projectionDistance * (-sourceY / projectionDistance);\n const length = Math.hypot(rx, ry, projectionDistance), t = subjectDistanceM / (projectionDistance / length);\n out[0] = rx / length * t / metresPerFrameUnit; out[1] = ry / length * t / metresPerFrameUnit;\n };\n return { offsets, signalInput: { nativeWidth: input.nativeWidth, nativeHeight: input.nativeHeight, outputWidth: input.width, wavelengthsNm: wavelengths,\n electronsPerRadiance: input.perNode, offsets, ...(kernels ? { kernels } : { queryPoint }), scene, channelAt: channelIndex } };\n}\n"]}
|