Headless 3D and VFX engine for agents. Research preview.
vork 0.2.0
Ravi Parikha18cac5d68ea
diff --git a/Cargo.lock b/Cargo.lockindex 15801d2..92ff76d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1754,19 +1754,13 @@ dependencies = [[[package]]name = "tokio"-version = "1.54.0"+version = "1.54.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"dependencies = ["pin-project-lite",]-[[package]]-name = "ttf-parser"-version = "0.25.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"-[[package]]name = "unarray"version = "0.1.4"@@ -1805,7 +1799,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"[[package]]name = "vork-cli"-version = "0.1.0"+version = "0.2.0"dependencies = ["anyhow","blake3",@@ -1820,7 +1814,7 @@ dependencies = [[[package]]name = "vork-encode"-version = "0.1.0"+version = "0.2.0"dependencies = ["anyhow","ash",@@ -1833,7 +1827,7 @@ dependencies = [[[package]]name = "vork-mesh"-version = "0.1.0"+version = "0.2.0"dependencies = ["anyhow","glam",@@ -1844,7 +1838,7 @@ dependencies = [[[package]]name = "vork-render"-version = "0.1.0"+version = "0.2.0"dependencies = ["anyhow","ash",@@ -1878,7 +1872,7 @@ dependencies = [[[package]]name = "vork-scene"-version = "0.1.0"+version = "0.2.0"dependencies = ["anyhow","glam",@@ -1889,9 +1883,10 @@ dependencies = [[[package]]name = "vork-slang"-version = "0.1.0"+version = "0.2.0"dependencies = ["anyhow",+ "blake3","libc","naga","serde",@@ -1901,7 +1896,7 @@ dependencies = [[[package]]name = "vork-std"-version = "0.1.0"+version = "0.2.0"dependencies = ["anyhow","blake3",@@ -1914,7 +1909,7 @@ dependencies = ["rquickjs","serde","serde_json",- "ttf-parser",+ "xberg-ttf-parser",][[package]]@@ -2289,6 +2284,12 @@ dependencies = ["windows-link",]+[[package]]+name = "xberg-ttf-parser"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92b07d4e7aae5dd7a6c145dfbce4f5dbec692b5e1bb56149841401c4f197956b"+[[package]]name = "xml-rs"version = "0.8.29"diff --git a/Cargo.toml b/Cargo.tomlindex 7107794..d74cd82 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -4,7 +4,7 @@ members = ["crates/*"]exclude = ["vendor/wgpu", "vendor/wgpu-core", "vendor/wgpu-hal", "vendor/wgpu-types", "vendor/basisu_c_sys", "vendor/exr"][workspace.package]-version = "0.1.0"+version = "0.2.0"edition = "2024"license = "LicenseRef-vork-Preview"publish = falsediff --git a/NOTICE b/NOTICEindex a5a443a..5951b0d 100644--- a/NOTICE+++ b/NOTICE@@ -62956,7 +62956,7 @@ usda/*.tif========================================================================-tokio 1.54.0+tokio 1.54.1SPDX: MITSource: https://github.com/tokio-rs/tokio@@ -62984,238 +62984,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-========================================================================-ttf-parser 0.25.1-SPDX: MIT OR Apache-2.0-Source: https://github.com/harfbuzz/ttf-parser----- LICENSE-APACHE ---- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.--Copyright [yyyy] [name of copyright owner]--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.------ LICENSE-MIT ----Copyright (c) 2018 Yevhenii Reizner--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in-all copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN-THE SOFTWARE.---========================================================================unicode-ident 1.0.27SPDX: (MIT OR Apache-2.0) AND Unicode-3.0@@ -70328,6 +70096,36 @@ Source: https://github.com/microsoft/windows-rsSOFTWARE+========================================================================+xberg-ttf-parser 1.1.0+SPDX: MIT+Source: https://github.com/xberg-io/xberg++--- LICENSE ---+MIT License++Copyright (c) 2025-2026 Kreuzberg, Inc.+Copyright (c) 2018 Yevhenii Reizner and the ttf-parser contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.++========================================================================xml-rs 0.8.29SPDX: MITdiff --git a/README.md b/README.mdindex 73c41ba..3e6b199 100644--- a/README.md+++ b/README.md@@ -21,7 +21,7 @@ everything else that moves is rendered.[Install vork](#install), then paste:-> Read `vork help`. Make a small scene, render a preview and inspect the image.+> Run `vork init my-shot`, read `vork help`, render a preview and inspect the image.> Refine the camera and lighting before rendering at final quality. Read the> relevant help topic when you need a feature the first page doesn't explain.@@ -41,6 +41,31 @@ the programming hooks are there when the shot needs something unusual.Source-available and free during the research preview.+## Start here++After [installing vork](#install), create a working project:++```sh+vork init my-shot+cd my-shot+vork render scene.json --profile std/draft --out render.png+vork help+```++Open `render.png`, change a colour or camera position in `scene.json`, and render+again. The starter uses only bundled sphere, box and grid primitives: no downloads,+no GPU needed to initialize. Use `vork init my-shot --language typescript` or+`--language python` for editable `scene.ts` or `scene.py` alongside the ready-to-render+JSON. The generated README explains regeneration and SDK requirements. Existing+files are never overwritten. Use `--profile std/final` for a cleaner image.++With the candidate npm packages (not yet published), `npm create vork my-shot`+creates the same project and installs its matching native engine and TypeScript SDK+from npm's cache, without network access during initialization. Then use+`npx vork render scene.json --profile std/draft --out render.png` and `npx vork help`+in the new directory. Pass `-- --language typescript` or `-- --language python`+to select source authoring. Python source needs the Python SDK as well.+## What you can makeThe examples include code, preparation commands and credits. Large downloaded@@ -139,20 +164,24 @@ A GPU liquid simulation implemented as Slang compute programs in vork's fluid liIt uses published APIC/FLIP and surface-reconstruction methods, with an authoredinitial impulse and limited secondary spray.+## No suitable GPU?++Rendering requires Apple Silicon or an NVIDIA GPU with Vulkan ray queries.+Scene authoring and `vork help` work without a GPU. On your own NVIDIA Linux+machine, you can use the [Docker runtime](docs/REMOTE-GPU.md).+Hosted rendering: details will be added here when available.+## Give it to an agent-Start with `vork help`. The getting-started help is about **2,500 tokens**,-including a complete first scene. Root, topic and command help total about-**19,500 tokens**; detailed field lookups add more. These are release 0.1.0-counts with the o200k_base tokenizer, not a measure of the whole API. The aggregate-concatenates `vork help`, each listed topic except `field` with `--all`, and `--help` for-render/std/setup/help. `vork help field material.inputs` includes another 38-lookup-only records (about 1,800 tokens).+Start with `vork init`, then `vork help`. Scene JSON uses the stable+[editor schema](https://voyager.so/vork/schema/scene.schema.json).+Use `vork help` for the starting scene and concepts, `vork help TOPIC --all`+for topic fields, and `vork help field PATH` for an exact field reference.Use the [prompt above](#paste-this-to-your-agent) to start.Python and TypeScript can author ordinary scene JSON through the SDKs. You can-also write JSON directly. Save this as `shot.json` (also available as+also write JSON directly. For example, save this as `scene.json` (also available as[examples/first-scene.json](examples/first-scene.json)):```json@@ -168,8 +197,8 @@ also write JSON directly. Save this as `shot.json` (also available as``````sh-vork render shot.json --profile std/previs --out preview.png-vork render shot.json --profile std/final --out final.png+vork render scene.json --profile std/previs --out preview.png+vork render scene.json --profile std/final --out final.pngvork help sdkvork help programs --all```@@ -206,7 +235,7 @@ exact.## Speed, with the qualificationsThese are timings, **not equal-quality speedups**. The draft/final results-come from the frozen `81ae2b075` build on an NVIDIA L4: final uses eight samples+come from the build identified by SHA-256 in the results report on an NVIDIA L4: final uses eight samplesand OIDN, draft four and OIDN. All 152 planned jobs were accounted for. The broadersweep delivered 583 of 585 images; the million-stars stress scene ran out of GPUmemory in both profiles. Visual review found softer edges, grainier defocus,@@ -255,9 +284,9 @@ Different quality and timing boundaries still apply.### Path tracing: carried-forward measurements-These 1080p still timings were measured in an earlier freeze, not on that-build. Adaptive sampling up to 4,096, threshold 0.01, minimum 64; stopping-implementations differ. vork is slower in both cases below.+These 1080p still timings were measured in an earlier build, rather than the+measured final build. Adaptive sampling up to 4,096, threshold 0.01, minimum 64;+stopping implementations differ. vork is slower in both cases below.| Scene input | Cycles (s) | vork path (s) | Comparison ||---|---:|---:|---|@@ -274,7 +303,7 @@ first final still took 82.057 s, versus its 1.787 s warm median.### Previews: carried-forward measurements-These are prior-freeze `std/previs` results, not measured on `81ae2b075`. Previews+These are earlier-build `std/previs` results, not measured on the final build identified in [RESULTS.md](benchmarks/RESULTS.md). Previewsuse different lighting and shadows; these are not final-quality comparisons.Complete 240-frame, 1080p24 movies, median of three warm commands:@@ -291,7 +320,7 @@ Complete 240-frame, 1080p24 movies, median of three warm commands:| [B-turntable.json](benchmarks/B-turntable.json) | 4.612 || [B-walking.json](benchmarks/B-walking.json) | 2.190 |-Across the seven simple preview clips in that prior freeze, EEVEE/vork was+Across the seven simple preview clips on that earlier build, EEVEE/vork was14.63–36.40× and Workbench/vork 3.99–11.24×. Those ranges use retained Blenderbaselines and different rendering settings and timing boundaries. They do notdescribe default final rendering.@@ -366,6 +395,8 @@ features. Read `vork help limits` before committing to a shot.## Install+Upgrading scenes or scripts? Run `vork help upgrade` ([upgrade guide](docs/help/upgrade.md)).+Binary packages are available from [GitHub Releases](https://github.com/voyager-so/vork/releases)once a release is published. Keep the entire install folder together: Slang, OIDN,libraries, examples, SDKs and licence texts are runtime companions to the binary.@@ -456,8 +487,6 @@ vork --versionvork help```-These dependency commands are for Ubuntu with sudo. In a root container, omit-`sudo`; without administrator access, arrange for the dependencies to be installed.The installer itself runs in your user account without root.The installer verifies SHA256SUMS, installs under `%LOCALAPPDATA%\Programs\vork`,@@ -474,8 +503,8 @@ Download the Windows `.zip` and `SHA256SUMS` from the release page. Compare`Get-FileHash .\vork-*-windows-x64.zip -Algorithm SHA256` with its entry in`SHA256SUMS`, then unzip the entire contents into `%LOCALAPPDATA%\Programs\vork`.Add that folder to your user PATH, open a new PowerShell window, and run-`vork setup`. It prints its report right away, then compiles for up to about 3 minutes-with no output until `Shader setup completed`; that isn't a hang. Keep all bundled+`vork setup`. It prints its report right away, then reports compilation progress until+`Shader setup completed`. Setup can take several minutes. Keep all bundledruntime companions beside the executable.The separately downloadable `install.sh` downloads the release from GitHub; to install an archive you already@@ -508,27 +537,34 @@ vork --versionvork setup```-`vork setup` prints its report right away, then compiles for up to about 3 minutes-with no output until `Shader setup completed`; that isn't a hang.+`vork setup` prints its report right away, then reports compilation progress until+`Shader setup completed`. Setup can take several minutes.++### npm and pip installation candidate++Registry packaging is being validated privately and has not been published.+Use the archive installers above and their bundled SDKs. npm and PyPI installation+will become available only after separate release approval.+These commands are not yet the default installation instructions.### First render and SDKs-Save the first scene above as `shot.json`, then:+Start with `vork init my-shot` and enter `my-shot`, then:```sh-vork render shot.json --profile std/previs --out preview.png-vork render shot.json --profile std/final --out final.png-vork render shot.json --profile std/final --frame-start 0 --frame-end 47 --out clip.mp4+vork render scene.json --profile std/previs --out preview.png+vork render scene.json --profile std/final --out final.png+vork render scene.json --profile std/final --frame-start 0 --frame-end 23 --out clip.mp4vork help animationvork help outputs```-The first render of a scene with new programs can compile for several minutes and-prints nothing while it does (about 3–4 minutes with custom programs on NVIDIA in our-tests, under 20 seconds on a Mac). It isn't hung, so don't kill it or give it a short-timeout. Later renders of the same programs take seconds.+The first render of a scene with new programs can compile for several minutes.+Progress reports show shader and driver pipeline preparation; allow time for it to+finish. Later renders reuse compiled programs and driver caches. Compilation time+depends on the scene, GPU and cache state.-Frame ranges include both endpoints: `0` through `47` writes 48 frames. The simple scene+Frame ranges include both endpoints: `0` through `23` writes 24 frames. The simple sceneis static; animation tracks make a moving clip. To try glTF import, save a modelas `model.glb` beside this scene as `model.json`:@@ -548,8 +584,8 @@ Adjust the camera and light for your model's scale. glTF files can refer totextures and buffers beside them; keep those files together.Run `vork setup` again after upgrading or changing GPU drivers. It prints its report-right away, then compiles for up to about 3 minutes with no output until-`Shader setup completed`; that isn't a hang. Vulkan persists+right away, then reports compilation progress until `Shader setup completed`.+Setup can take several minutes. Vulkan persistsits pipeline cache when supported; Metal warms the system driver cache. New sceneprograms can still require compilation on their first render. `VORK_CACHE_DIR`overrides the cache location.@@ -568,7 +604,7 @@ The SDKs install from your vork folder, not from npm or PyPI. The npm package naOn Windows use `py -m pip install "$env:LOCALAPPDATA\Programs\vork\python"` and`npm install "$env:LOCALAPPDATA\Programs\vork\sdk"`. Import as `vork` in Python or-`@usevoyager/vork` in TypeScript; keep the native executable on PATH.+`@voyager-so/vork` in TypeScript; keep the native executable on PATH.For source builds, see [`vork help build`](docs/help/build.md).## Licencediff --git a/benchmarks/RESULTS.md b/benchmarks/RESULTS.mdindex 99b340f..ca7697d 100644--- a/benchmarks/RESULTS.md+++ b/benchmarks/RESULTS.md@@ -1,16 +1,15 @@# Benchmark results-Measured renderer: `81ae2b0755bb696fc3e904744b76a103feded023`.Linux NVIDIA L4, four CPUs, 32 GiB per worker; seed 11.Binary SHA-256: `e4d4e5fb585de30ea7f9e69e874ddee1951e046a6dc9441ee1563c90bfe5e115`.Raw logs, measurements and contact sheets are not in this repository.Ranges are observed minima/maxima, not confidence intervals. See the READMEfor timing boundaries, quality differences, limitations and rerun recipes.-New final uses eight samples + OIDN; draft four + OIDN. Preview and path+The measured final profile used eight samples + OIDN; draft four + OIDN. Preview and pathresults are carried forward and were not remeasured on this build.-## New std/final vs EEVEE — seven full movies+## std/final vs EEVEE — seven full movies| Scene | Warm final s (measured) | First after setup s | Setup s | EEVEE s (reused measured) | Comparison | Prior 32-sample final s | Change in command time ||---|---|---|---|---|---|---|---|@@ -72,35 +71,35 @@ Three complete movies per shot. Skim 192 frames, dive 240, reveal 288, at 24 fps## Carried-forward std/previs-| Cell | Warm s (prior freeze measured) | EEVEE comparison where available |+| Cell | Warm s (earlier build) | EEVEE comparison where available ||---|---|---|| bird-skim-previs | 48.990 [46.473–49.020], n=3 | unmeasured || bird-birds2-previs | 50.127 [50.093–50.204], n=3 | unmeasured |-| preview7-D-cube-still | 1.284 [1.234–1.286], n=5 | see previous report |+| preview7-D-cube-still | 1.284 [1.234–1.286], n=5 | comparison not published || preview7-D-cube-video | 3.062 [2.949–3.321], n=3 | unmeasured |-| preview7-B-blocking-still | 1.030 [1.029–1.078], n=5 | see previous report |+| preview7-B-blocking-still | 1.030 [1.029–1.078], n=5 | comparison not published || preview7-B-blocking-video | 3.496 [3.495–3.498], n=3 | unmeasured |-| preview7-B-interior-still | 1.337 [1.234–1.433], n=5 | see previous report |+| preview7-B-interior-still | 1.337 [1.234–1.433], n=5 | comparison not published || preview7-B-interior-video | 4.565 [4.507–4.659], n=3 | unmeasured |-| preview7-B-car-pan-still | 1.285 [1.234–1.340], n=5 | see previous report |+| preview7-B-car-pan-still | 1.285 [1.234–1.340], n=5 | comparison not published || preview7-B-car-pan-video | 6.391 [6.187–6.584], n=3 | unmeasured |-| preview7-B-night-still | 1.333 [1.282–1.389], n=5 | see previous report |+| preview7-B-night-still | 1.333 [1.282–1.389], n=5 | comparison not published || preview7-B-night-video | 5.864 [5.808–5.931], n=3 | unmeasured |-| preview7-C-ToyCar-still | 1.542 [1.485–1.591], n=5 | see previous report |+| preview7-C-ToyCar-still | 1.542 [1.485–1.591], n=5 | comparison not published || preview7-C-ToyCar-video | 4.107 [4.103–4.158], n=3 | unmeasured |-| preview7-C-SheenChair-still | 1.030 [1.029–1.032], n=5 | see previous report |+| preview7-C-SheenChair-still | 1.030 [1.029–1.032], n=5 | comparison not published || preview7-C-SheenChair-video | 3.013 [2.947–3.043], n=3 | unmeasured |-| repo-B-crowd-previs-still | 1.132 [1.079–1.185], n=5 | see previous report |+| repo-B-crowd-previs-still | 1.132 [1.079–1.185], n=5 | comparison not published || repo-B-crowd-previs-video | 4.097 [4.056–4.267], n=3 | unmeasured |-| repo-B-push-in-previs-still | 1.385 [1.337–1.434], n=5 | see previous report |+| repo-B-push-in-previs-still | 1.385 [1.337–1.434], n=5 | comparison not published || repo-B-push-in-previs-video | 3.705 [3.700–3.711], n=3 | unmeasured |-| repo-B-rack-focus-previs-still | 1.285 [1.233–1.388], n=5 | see previous report |+| repo-B-rack-focus-previs-still | 1.285 [1.233–1.388], n=5 | comparison not published || repo-B-rack-focus-previs-video | 3.902 [3.799–3.907], n=3 | unmeasured |-| repo-B-street-previs-still | 1.283 [1.231–1.391], n=5 | see previous report |+| repo-B-street-previs-still | 1.283 [1.231–1.391], n=5 | comparison not published || repo-B-street-previs-video | 3.964 [3.953–4.061], n=3 | unmeasured |-| repo-B-turntable-previs-still | 1.334 [1.333–1.341], n=5 | see previous report |+| repo-B-turntable-previs-still | 1.334 [1.333–1.341], n=5 | comparison not published || repo-B-turntable-previs-video | 4.612 [4.563–4.712], n=3 | unmeasured |-| repo-B-walking-previs-still | 1.346 [1.281–1.441], n=5 | see previous report |+| repo-B-walking-previs-still | 1.346 [1.281–1.441], n=5 | comparison not published || repo-B-walking-previs-video | 2.190 [2.190–2.238], n=3 | unmeasured |## Carried-forward std/path@@ -137,4 +136,4 @@ Three complete movies per shot. Skim 192 frames, dive 240, reveal 288, at 24 fps| D-cube | 9.253 [9.156–9.604], n=5 | 2.558 | 3.62× slower || D-Duck | 10.008 [9.349–10.715], n=5 | unmeasured | unmeasured |-Path timings originated in frozen-44ccb8d57 and were already carried forward by frozen-04a1a993a. They are not measured on this commit.+These path timings were measured on an earlier build, not the renderer identified above. Re-run both tools with the supplied inputs before drawing conclusions about current performance.diff --git a/benchmarks/birds/historical.json b/benchmarks/birds/historical.jsondeleted file mode 100644index 6470598..0000000--- a/benchmarks/birds/historical.json+++ /dev/null@@ -1,213 +0,0 @@-{- "status": "pending re-measure on frozen release build",- "historical_only": true,- "birds2": [- {- "engine": "eevee",- "samples": 16,- "measured_frames": 9,- "warm_frames": 8,- "first_s": 43.957634257,- "warm_mean_s": 9.614078758375001,- "extrapolated_192_warm_s": 1845.9031216080002,- "ratio_to_corresponding_vork_movie": 7.497345416132144,- "baseline_s": 246.20756003- },- {- "engine": "eevee",- "samples": 4,- "measured_frames": 8,- "warm_frames": 8,- "first_s": null,- "warm_mean_s": 5.628966662,- "extrapolated_192_warm_s": 1080.761599104,- "ratio_to_corresponding_vork_movie": 21.00795615687386,- "baseline_s": 51.445347231- },- {- "engine": "eevee-previs",- "samples": 4,- "measured_frames": 9,- "warm_frames": 8,- "first_s": 19.60573525999999,- "warm_mean_s": 5.644220466499995,- "extrapolated_192_warm_s": 1083.690329567999,- "ratio_to_corresponding_vork_movie": 21.064885123663576,- "baseline_s": 51.445347231- },- {- "engine": "cycles",- "samples": 16,- "measured_frames": 4,- "warm_frames": 3,- "first_s": 40.608326014,- "warm_mean_s": 38.125282511,- "extrapolated_192_warm_s": 7320.054242112001,- "ratio_to_corresponding_vork_movie": 29.731232628356594,- "baseline_s": 246.20756003- }- ],- "birds3": [- {- "shot": "skim",- "vork": {- "frames": 192,- "seconds": 8,- "movie_s": 243.449527497,- "warmup_s": 179.208225653,- "previs_s": 51.617237647,- "previs_warmup_s": 77.660048198- },- "blender": [- {- "shot": "skim",- "mode": "eevee",- "samples": 16,- "raytracing": true,- "warm_frames": 8,- "first_s": 30.477487675000006,- "warm_mean_s": 7.870355238000002,- "warm_min_s": 6.6276457710000045,- "warm_max_s": 8.591802177000005,- "update_mean_s": 0.22291857750000688,- "projected_s": 1511.1082056960004,- "projected_first_plus_warm_s": 1533.7153381330004,- "vork_s": 243.449527497,- "ratio": 6.207069782522464- },- {- "shot": "skim",- "mode": "eevee",- "samples": 4,- "raytracing": true,- "warm_frames": 8,- "warm_mean_s": 4.029599970999996,- "warm_min_s": 3.727960104999994,- "warm_max_s": 4.373036377999995,- "update_mean_s": 0.21976194837499818,- "projected_s": 773.6831944319993,- "vork_s": 51.617237647,- "ratio": 14.988853137067588- },- {- "shot": "skim",- "mode": "eevee-previs",- "samples": 4,- "raytracing": false,- "warm_frames": 8,- "first_s": 13.497261533,- "warm_mean_s": 4.119593271124998,- "warm_min_s": 3.903837095,- "warm_max_s": 4.3000114499999995,- "update_mean_s": 0.219846653500003,- "projected_s": 790.9619080559996,- "projected_first_plus_warm_s": 800.3395763178746,- "vork_s": 51.617237647,- "ratio": 15.3236001016798- },- {- "shot": "skim",- "mode": "cycles",- "samples": 16,- "raytracing": true,- "warm_frames": 3,- "first_s": 33.687656222000044,- "warm_mean_s": 31.81301350899999,- "warm_min_s": 31.312078843999984,- "warm_max_s": 32.14273792099999,- "update_mean_s": 0.2264111606666764,- "projected_s": 6108.098593727998,- "projected_first_plus_warm_s": 6109.973236440998,- "vork_s": 243.449527497,- "ratio": 25.089794408425245- }- ]- },- {- "shot": "dive",- "vork": {- "frames": 240,- "seconds": 10,- "movie_s": 335.462539152,- "warmup_s": 172.63186151- },- "blender": [- {- "shot": "dive",- "mode": "eevee",- "samples": 16,- "raytracing": true,- "warm_frames": 8,- "first_s": 43.626787014,- "warm_mean_s": 10.491211330125008,- "warm_min_s": 8.419319722000012,- "warm_max_s": 12.466333617000004,- "update_mean_s": 0.3804740960000004,- "projected_s": 2517.890719230002,- "projected_first_plus_warm_s": 2551.026294913877,- "vork_s": 335.462539152,- "ratio": 7.505728435714044- },- {- "shot": "dive",- "mode": "cycles",- "samples": 16,- "raytracing": true,- "warm_frames": 3,- "first_s": 41.04882040199999,- "warm_mean_s": 38.10070456033333,- "warm_min_s": 38.021004764,- "warm_max_s": 38.18085367600003,- "update_mean_s": 0.38406866233333403,- "projected_s": 9144.16909448,- "projected_first_plus_warm_s": 9147.117210321665,- "vork_s": 335.462539152,- "ratio": 27.258391108572408- }- ]- },- {- "shot": "reveal",- "vork": {- "frames": 288,- "seconds": 12,- "movie_s": 403.163022336,- "warmup_s": 114.672536779- },- "blender": [- {- "shot": "reveal",- "mode": "eevee",- "samples": 16,- "raytracing": true,- "warm_frames": 8,- "first_s": 43.66385206299998,- "warm_mean_s": 10.125821887249995,- "warm_min_s": 6.871748912999976,- "warm_max_s": 12.12216495300001,- "update_mean_s": 0.38926759750000883,- "projected_s": 2916.2367035279985,- "projected_first_plus_warm_s": 2949.7747337037486,- "vork_s": 403.163022336,- "ratio": 7.23339329740806- },- {- "shot": "reveal",- "mode": "cycles",- "samples": 16,- "raytracing": true,- "warm_frames": 3,- "first_s": 40.62449904199997,- "warm_mean_s": 39.770884482999996,- "warm_min_s": 39.27429363599998,- "warm_max_s": 40.50851037699999,- "update_mean_s": 0.41112854866666265,- "projected_s": 11454.014731103998,- "projected_first_plus_warm_s": 11454.868345662999,- "vork_s": 403.163022336,- "ratio": 28.410380160207527- }- ]- }- ]-}diff --git a/benchmarks/claims.json b/benchmarks/claims.jsondeleted file mode 100644index a6dba2a..0000000--- a/benchmarks/claims.json+++ /dev/null@@ -1,36 +0,0 @@-{- "status": "Final draft4/final8 results recorded; preview/path carried forward; Blender baselines retained",- "claims": [- {- "claim": "Default final seven 240-frame clips: EEVEE/vork 1.14\u20132.32x",- "qualification": "Measured final8 + OIDN on 81ae2b075; retained measured EEVEE with different settings/timing boundaries. Not equal quality.",- "results": "RESULTS.md"- },- {- "claim": "Bird skim/dive/reveal: 96.942/124.718/153.411 seconds",- "inputs": [- "birds/skim.json.in",- "birds/dive.json.in",- "birds/reveal.json.in"- ],- "qualification": "Measured draft4 + OIDN, excludes separate setup and still warmup. EEVEE comparisons are eight-frame projections excluding simulation/startup/encoding.",- "results": "RESULTS.md"- },- {- "claim": "Preview EEVEE/vork 14.63\u201336.40x; Workbench/vork 3.99\u201311.24x",- "qualification": "Carried-forward prior-freeze preview measurements and retained Blender baselines; different quality and timing boundaries. Not default-final speed.",- "results": "RESULTS.md"- },- {- "claim": "Named historical path cases are slower than Cycles",- "inputs": [- "B-blocking.json",- "B-car-pan.json",- "B-night.json"- ],- "qualification": "Carried forward, not remeasured on final4. All slower cases retained.",- "results": "RESULTS.md"- }- ],- "results": "RESULTS.md"-}diff --git a/benchmarks/historical.json b/benchmarks/historical.jsondeleted file mode 100644index a8feb19..0000000--- a/benchmarks/historical.json+++ /dev/null@@ -1,1234 +0,0 @@-{- "status": "pending re-measure on the frozen release build",- "renderer_commit": "0b983bcfde6f32d4dbdf852a5c6b8758d235ab25",- "blender_version": "5.2.1",- "gpu": "NVIDIA L4",- "quality": "not equal-quality; all 19 quality comparisons failed the declared no-worse FLIP condition",- "rows": [- {- "scene": "B-blocking",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 5.190721074999999,- "min_s": 5.143397821000008,- "max_s": 5.298426681000024,- "failures": []- },- {- "scene": "B-blocking",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 5.257902380000019,- "min_s": 5.189505538000006,- "max_s": 5.299544929999996,- "failures": []- },- {- "scene": "B-blocking",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 92.74213059200002,- "min_s": 90.59369564600001,- "max_s": 95.066859803,- "failures": []- },- {- "scene": "B-blocking",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 23.497012571,- "min_s": 23.125525037999978,- "max_s": 24.084926902999996,- "failures": []- },- {- "scene": "B-blocking",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 116.71972331200001,- "min_s": 113.85396473700001,- "max_s": 123.968679963,- "failures": []- },- {- "scene": "B-blocking",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.4581080510000106,- "min_s": 2.3007279159999996,- "max_s": 2.553526237,- "failures": []- },- {- "scene": "B-blocking",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.404634525000006,- "min_s": 2.3036388480000056,- "max_s": 2.6073817840000117,- "failures": []- },- {- "scene": "B-blocking",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 62.37022005099996,- "min_s": 61.01990152900001,- "max_s": 64.57678502400003,- "failures": []- },- {- "scene": "B-blocking",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 1.8928627450000022,- "min_s": 1.7361441440000078,- "max_s": 1.89444914500001,- "failures": []- },- {- "scene": "B-blocking",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 109.91812777799998,- "min_s": 108.364129599,- "max_s": 115.241434336,- "failures": []- },- {- "scene": "B-car-pan",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 4.633844818,- "min_s": 4.370096969999992,- "max_s": 5.711945402000026,- "failures": []- },- {- "scene": "B-car-pan",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 4.6318185690000035,- "min_s": 4.374900793999998,- "max_s": 5.451244876000004,- "failures": []- },- {- "scene": "B-car-pan",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 82.18517233400001,- "min_s": 66.93237346899997,- "max_s": 99.33452868199998,- "failures": []- },- {- "scene": "B-car-pan",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 24.678709301000012,- "min_s": 23.780611731000008,- "max_s": 26.93481064300002,- "failures": []- },- {- "scene": "B-car-pan",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 108.49055411100002,- "min_s": 74.073570191,- "max_s": 120.75995379999998,- "failures": []- },- {- "scene": "B-car-pan",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.453912900000006,- "min_s": 1.8412719879999884,- "max_s": 2.7055896080000252,- "failures": []- },- {- "scene": "B-car-pan",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.4575511449999965,- "min_s": 1.7893410679999988,- "max_s": 2.6592572070000102,- "failures": []- },- {- "scene": "B-car-pan",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 65.57232350999999,- "min_s": 42.77297841800001,- "max_s": 73.77581199500003,- "failures": []- },- {- "scene": "B-car-pan",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 6.107079243000001,- "min_s": 5.547018295000001,- "max_s": 6.276517865000002,- "failures": []- },- {- "scene": "B-car-pan",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 117.968421159,- "min_s": 72.981416558,- "max_s": 122.87823452599997,- "failures": []- },- {- "scene": "B-interior",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 3- ],- "rows": 4,- "median_s": 2.8124134660000095,- "min_s": 2.204347361999993,- "max_s": 3.0145870549999927,- "failures": []- },- {- "scene": "B-interior",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 3- ],- "rows": 4,- "median_s": 2.891689904499998,- "min_s": 1.9416498829999966,- "max_s": 3.173053381999992,- "failures": []- },- {- "scene": "B-interior",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 3- ],- "rows": 4,- "median_s": 67.2016741835,- "min_s": 40.26911803500002,- "max_s": 80.88899227900004,- "failures": []- },- {- "scene": "B-interior",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 3- ],- "rows": 4,- "median_s": 2.6780054279999916,- "min_s": 2.4438605379999956,- "max_s": 2.8000213460000083,- "failures": []- },- {- "scene": "B-interior",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 3- ],- "rows": 4,- "median_s": 120.19751590949998,- "min_s": 73.426272392,- "max_s": 139.24557513399998,- "failures": []- },- {- "scene": "B-night",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 16.041967372999977,- "min_s": 15.87104973999999,- "max_s": 16.87885267400003,- "failures": []- },- {- "scene": "B-night",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 16.040989578999998,- "min_s": 15.924136691000001,- "max_s": 17.096823905000008,- "failures": []- },- {- "scene": "B-night",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 72.555925124,- "min_s": 71.41812104800002,- "max_s": 105.92580616600003,- "failures": []- },- {- "scene": "B-night",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 30.142142164000006,- "min_s": 29.894445680000004,- "max_s": 30.81274024000001,- "failures": []- },- {- "scene": "B-night",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 76.149909715,- "min_s": 70.19500050600001,- "max_s": 116.63169142100003,- "failures": []- },- {- "scene": "B-night",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 3.1748034479999774,- "min_s": 2.8590502639999897,- "max_s": 3.6811548870000195,- "failures": []- },- {- "scene": "B-night",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.9630759939999933,- "min_s": 2.910975722999993,- "max_s": 3.1155768530000074,- "failures": []- },- {- "scene": "B-night",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 66.78773739899998,- "min_s": 63.98549617399999,- "max_s": 77.28372921399998,- "failures": []- },- {- "scene": "B-night",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 3.7675625769999925,- "min_s": 3.765244636999995,- "max_s": 3.8711776410000027,- "failures": []- },- {- "scene": "B-night",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 117.51408166799999,- "min_s": 115.84594998600002,- "max_s": 119.99273857699998,- "failures": []- },- {- "scene": "B-push-in",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 4.630554306999983,- "min_s": 4.369456778999989,- "max_s": 5.3990284409999845,- "failures": []- },- {- "scene": "B-push-in",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 4.424862046000001,- "min_s": 4.403513790999995,- "max_s": 5.3480286779999915,- "failures": []- },- {- "scene": "B-push-in",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 66.794256013,- "min_s": 63.66484049499999,- "max_s": 106.56467968600003,- "failures": []- },- {- "scene": "B-push-in",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 22.194921991,- "min_s": 21.543631321000007,- "max_s": 24.089826442000003,- "failures": []- },- {- "scene": "B-push-in",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 78.07097237300002,- "min_s": 67.475486093,- "max_s": 123.37523398399998,- "failures": []- },- {- "scene": "B-push-in",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.556688052000027,- "min_s": 1.7894705140000156,- "max_s": 2.9151670719999743,- "failures": []- },- {- "scene": "B-push-in",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.9121872860000053,- "min_s": 1.7943144490000122,- "max_s": 3.1667574290000005,- "failures": []- },- {- "scene": "B-push-in",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 63.99071766200001,- "min_s": 40.42223781299998,- "max_s": 66.68071271500003,- "failures": []- },- {- "scene": "B-push-in",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 1.9425185139999996,- "min_s": 1.6881981770000039,- "max_s": 2.2990633189999983,- "failures": []- },- {- "scene": "B-push-in",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 111.59757885500002,- "min_s": 74.810082136,- "max_s": 123.61400641099999,- "failures": []- },- {- "scene": "B-turntable",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 5.754983613000036,- "min_s": 4.58397041500001,- "max_s": 5.953873870999985,- "failures": []- },- {- "scene": "B-turntable",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 5.55527373999999,- "min_s": 4.645107959000001,- "max_s": 6.228357340999992,- "failures": []- },- {- "scene": "B-turntable",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 167.65104816100006,- "min_s": 114.92283981,- "max_s": 190.949859281,- "failures": []- },- {- "scene": "B-turntable",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 19.546711962000018,- "min_s": 19.074370095000006,- "max_s": 19.94550563300001,- "failures": []- },- {- "scene": "B-turntable",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 111.52553259000001,- "min_s": 71.928871756,- "max_s": 112.86770572,- "failures": []- },- {- "scene": "B-turntable",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 4- ],- "rows": 4,- "median_s": 3.0909588059999464,- "min_s": 2.7530961969999908,- "max_s": 3.4727050239999926,- "failures": []- },- {- "scene": "B-turntable",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 4- ],- "rows": 4,- "median_s": 3.147545813999983,- "min_s": 2.9583998690000044,- "max_s": 3.383579024000028,- "failures": []- },- {- "scene": "B-turntable",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 4- ],- "rows": 4,- "median_s": 446.0647363075001,- "min_s": 414.325280335,- "max_s": 487.7888623000001,- "failures": []- },- {- "scene": "B-turntable",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 4- ],- "rows": 4,- "median_s": 3.3114555835000203,- "min_s": 3.3032715089999556,- "max_s": 3.6672570229999337,- "failures": []- },- {- "scene": "B-turntable",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 4,- "reps": [- 0,- 1,- 2,- 4- ],- "rows": 4,- "median_s": 116.08448092600005,- "min_s": 109.28816693900006,- "max_s": 127.37667039999997,- "failures": []- },- {- "scene": "B-walking",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 3.0639156120000166,- "min_s": 2.3497434209999994,- "max_s": 3.621898005999981,- "failures": []- },- {- "scene": "B-walking",- "config": "path-4096-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 3.108468364999993,- "min_s": 2.453460262000007,- "max_s": 3.4670015009999986,- "failures": []- },- {- "scene": "B-walking",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 115.95911173899998,- "min_s": 74.08062934999998,- "max_s": 124.833809906,- "failures": []- },- {- "scene": "B-walking",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 9.811021965000009,- "min_s": 8.90347732699999,- "max_s": 10.971001597999987,- "failures": []- },- {- "scene": "B-walking",- "config": "path-4096-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 108.18514626500001,- "min_s": 74.67177425100002,- "max_s": 122.09234481000001,- "failures": []- },- {- "scene": "B-walking",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.2491016739999736,- "min_s": 1.6404863349999914,- "max_s": 2.6175261449999994,- "failures": []- },- {- "scene": "B-walking",- "config": "raster-64-1920x1080-png",- "tool": "blender",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 2.6116603779999537,- "min_s": 1.689736049000004,- "max_s": 3.0257182169999624,- "failures": []- },- {- "scene": "B-walking",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "after_setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 200.86324998900005,- "min_s": 133.446550388,- "max_s": 222.082704891,- "failures": []- },- {- "scene": "B-walking",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "rerender",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 3.050091521000013,- "min_s": 2.3396912569999984,- "max_s": 3.152894777999961,- "failures": []- },- {- "scene": "B-walking",- "config": "raster-64-1920x1080-png",- "tool": "vork",- "mode": "setup",- "successful_reps": 5,- "reps": [- 0,- 1,- 2,- 3,- 4- ],- "rows": 5,- "median_s": 106.77224324999997,- "min_s": 77.67435773,- "max_s": 120.80983652000003,- "failures": []- }- ]-}diff --git a/crates/vork-cli/Cargo.toml b/crates/vork-cli/Cargo.tomlindex 9a10cb7..6b5f588 100644--- a/crates/vork-cli/Cargo.toml+++ b/crates/vork-cli/Cargo.toml@@ -7,6 +7,7 @@ license.workspace = truename = "vork"path = "src/main.rs"[dependencies]+vork-slang = { path = "../vork-slang" }vork-render = { path = "../vork-render" }anyhow = "1"clap = { version = "4", features = ["derive"] }diff --git a/crates/vork-cli/build.rs b/crates/vork-cli/build.rsindex 7453d6a..e5819a9 100644--- a/crates/vork-cli/build.rs+++ b/crates/vork-cli/build.rs@@ -1,6 +1,6 @@use std::process::Command;-fn program_enum_help() {+fn program_input_help() {use std::{fmt::Write, path::Path};use vork_slang::{Abi, Compiler};let abi = Abi {@@ -17,6 +17,27 @@ fn program_enum_help() {.expect("reflect std/camera inputs");let mut text = String::new();for field in camera.inputs.fields {+ // Read initializers from the bundled source rather than duplicating camera defaults.+ let initializer = source.lines().find_map(|line| {+ let (declaration, value) = line.split_once('=')?;+ (declaration.split_whitespace().last()? == field.name)+ .then(|| value.split_once(';').expect("camera input initializer").0.trim())+ }).expect("bundled camera input has an initializer");+ let default = if field.enumeration.is_some() {+ initializer.rsplit('.').next().unwrap().to_ascii_lowercase()+ } else if let vork_slang::Type::Vector(n) = field.ty {+ let value = initializer.split_once('(').expect("camera vector initializer").1.trim_end_matches(')');+ let value: f64 = value.parse().expect("camera vector splat");+ format!("[{}]", vec![value.to_string(); n as usize].join(","))+ } else if matches!(field.ty, vork_slang::Type::Float) {+ initializer.parse::<f64>().expect("camera numeric initializer").to_string()+ } else { initializer.to_owned() };+ let units = match field.name.as_str() {+ "lens" | "sensor_width" | "sensor_height" => "; mm",+ "ortho_scale" | "clip_start" | "clip_end" | "focus_distance" => "; metres",+ "aperture_rotation" => "; radians",+ _ => "",+ };if let Some(enumeration) = field.enumeration {let tokens = enumeration.cases@@ -26,21 +47,30 @@ fn program_enum_help() {.join("|");writeln!(text,- "std/camera.{}: enum {tokens}; {} (JSON tokens).",+ "std/camera.{}: enum {tokens}; {} (JSON tokens); default {default}.",field.name, enumeration.ty).unwrap();+ } else {+ let ty = match field.ty {+ vork_slang::Type::Float => "number".to_owned(),+ vork_slang::Type::Uint => "uint".to_owned(),+ vork_slang::Type::Bool => "bool".to_owned(),+ vork_slang::Type::Vector(n) => format!("vec{n}"),+ ty => format!("{ty:?}"),+ };+ writeln!(text, "std/camera.{}: {ty}{units}; default {default}.", field.name).unwrap();}}std::fs::write(- Path::new(&std::env::var("OUT_DIR").unwrap()).join("program-enums.txt"),+ Path::new(&std::env::var("OUT_DIR").unwrap()).join("program-inputs.txt"),text,).unwrap();}fn main() {- program_enum_help();+ program_input_help();// Resolve the worktree HEAD on every build, including packed refs and detached HEADs.println!("cargo:rerun-if-changed=build.rs");for arg in ["HEAD", "refs", "packed-refs"] {diff --git a/crates/vork-cli/src/constants.rs b/crates/vork-cli/src/constants.rsindex a7eb657..691c18e 100644--- a/crates/vork-cli/src/constants.rs+++ b/crates/vork-cli/src/constants.rs@@ -1,5 +1,6 @@/// Public help topics; shared by root help and unknown-topic diagnostics.pub const HELP_TOPICS: &[&str] = &[+ "init","std","blender","fluid",@@ -8,6 +9,7 @@ pub const HELP_TOPICS: &[&str] = &["sdk","field","contract",+ "upgrade","nodes","lights","cameras",diff --git a/crates/vork-cli/src/help.rs b/crates/vork-cli/src/help.rsindex fcf1a66..93ff5d4 100644--- a/crates/vork-cli/src/help.rs+++ b/crates/vork-cli/src/help.rs@@ -1,15 +1,18 @@//! Concept help, with Rust-generated field facts and the actual program ABI on demand.-use anyhow::{Result, ensure};+use anyhow::Result;+use std::io::Write;use crate::{constants, help_text, root_help, topic_for_line};/// Every scene and settings field, one line each; generated by scripts/generate-docs.pub(crate) const REFERENCE: &str = include_str!("../../vork-scene/src/v2/reference.txt");-const PROGRAM_ENUMS: &str = include_str!(concat!(env!("OUT_DIR"),"/program-enums.txt"));+const PROGRAM_INPUTS: &str = include_str!(concat!(env!("OUT_DIR"),"/program-inputs.txt"));fn document(topic: &str) -> Option<&'static str> {Some(match topic {+ "init" => include_str!("../../../docs/help/init.md"),"build" => include_str!("../../../docs/help/build.md"),"limits" => include_str!("../../../docs/help/limits.md"),+ "upgrade" => include_str!("../../../docs/help/upgrade.md"),"contract" => include_str!("../../../docs/help/contract.md"),"nodes" => include_str!("../../../docs/help/nodes.md"),"cameras" => include_str!("../../../docs/help/cameras.md"),@@ -34,10 +37,26 @@ fn document(topic: &str) -> Option<&'static str> {}/// The field's own line, or for an object path (e.g. `render`) every field beneath it.fn field_lines(path: &str) -> Vec<&'static str> {+ let alias;+ let mut kind_alias = None;+ let path = if let Some((kind, tail)) = path.split_once('.') {+ if matches!(kind, "camera" | "mesh" | "light" | "asset") {+ kind_alias = Some(kind);+ alias = format!("node.{tail}");+ &alias+ } else { path }+ } else { path };let name = |line: &'static str| line.split_once(':').map(|(name, _)| name);- REFERENCE.lines().chain(PROGRAM_ENUMS.lines()).filter(|line| name(line).is_some_and(|name| name == path || {- name.strip_prefix(path).is_some_and(|rest| rest.starts_with('.') || rest.starts_with(' '))- })).collect()+ REFERENCE.lines().chain(PROGRAM_INPUTS.lines()).filter(|line| {+ if let Some(kind) = kind_alias {+ if let Some((_, annotation)) = name(line).unwrap_or("").split_once(" (") {+ if annotation != format!("{kind})") { return false; }+ }+ }+ name(line).is_some_and(|name| name == path || {+ name.strip_prefix(path).is_some_and(|rest| rest.starts_with('.') || rest.starts_with(' '))+ })+ }).collect()}/// Diagnose only failed help lookups; scene decoding keeps its own suggestions.fn unknown_field(path: &str) -> String {@@ -50,7 +69,7 @@ fn unknown_field(path: &str) -> String {fn wire_path(name: &str) -> &str { name.split_once(' ').map_or(name, |(path, _)| path) }fn leaf(name: &str) -> &str { wire_path(name).rsplit('.').next().unwrap_or(name) }fn area(name: &str) -> &str { name.split('.').next().unwrap_or(name) }- let mut names: Vec<_> = REFERENCE.lines()+ let mut names: Vec<_> = REFERENCE.lines().chain(PROGRAM_INPUTS.lines()).filter_map(|line| line.split_once(':').map(|(name, _)| name)).filter(|name| name.contains('.')).collect();let distance = vork_scene::diagnostics::distance;@@ -78,40 +97,50 @@ fn topic_lines(topic: &str) -> impl Iterator<Item = &'static str> + '_ {&& !vork_scene::v2::lookup_only_field(line))}pub fn run(topic: Option<&str>, field: Option<&str>, all: bool) -> Result<()> {- let result = serve(topic, field, all);- result.map_err(|e| e.context(vork_render::failure::FailureKind::Usage))+ serve(topic, field, all)?;+ std::io::stdout().flush().map_err(crate::output::error)+}+fn usage(message: impl std::fmt::Display) -> anyhow::Error {+ anyhow::anyhow!("{message}").context(vork_render::failure::FailureKind::Usage)}fn serve(topic: Option<&str>, field: Option<&str>, all: bool) -> Result<()> {- ensure!(field.is_none() || topic == Some("field"), "extra argument requires `vork help field PATH`");- let Some(topic) = topic else { print!("{}", root_help()); return Ok(()); };+ if field.is_some() && topic != Some("field") { return Err(usage("extra argument requires `vork help field PATH`")); }+ let topic = match topic {+ Some("std/bloom") => return serve(Some("compositor"), None, true),+ Some("std/camera") => return serve(Some("cameras"), None, true),+ topic => topic,+ };+ let stdout = std::io::stdout();+ let mut out = stdout.lock();+ let Some(topic) = topic else { write!(out, "{}", root_help()).map_err(crate::output::error)?; return Ok(()); };if topic == "field" {- let path = field.ok_or_else(|| anyhow::anyhow!("use `vork help field PATH`, e.g. node.target"))?;+ let path = field.ok_or_else(|| usage("use `vork help field PATH`, e.g. node.target"))?;let lines = field_lines(path);- ensure!(!lines.is_empty(), "{}", unknown_field(path));- for line in lines { println!("{line}"); }+ if lines.is_empty() { return Err(usage(unknown_field(path))); }+ for line in lines { writeln!(out, "{line}").map_err(crate::output::error)?; }return Ok(());}if let Some(library) = vork_scene::libraries::library(topic) {let (summary, details) = library.help.split_once("<!-- all -->").unwrap_or((library.help, ""));- print!("{}", help_text(summary));+ write!(out, "{}", help_text(summary)).map_err(crate::output::error)?;if all {- print!("{}", help_text(details));- for line in topic_lines(topic) { println!("{line}"); }- if topic == "std" { print!("\n{}{}", PROGRAM_ENUMS, help_text(crate::std_command::HELP)); }+ write!(out, "{}", help_text(details)).map_err(crate::output::error)?;+ for line in topic_lines(topic) { writeln!(out, "{line}").map_err(crate::output::error)?; }+ if topic == "std" { write!(out, "\n{}{}", PROGRAM_INPUTS, help_text(crate::std_command::HELP)).map_err(crate::output::error)?; }}return Ok(());}let Some(text) = document(topic) else {- anyhow::bail!("{}", vork_scene::diagnostics::unknown("help topic", topic, constants::HELP_TOPICS.iter().copied()));+ return Err(usage(vork_scene::diagnostics::unknown("help topic", topic, constants::HELP_TOPICS.iter().copied())));};// A page's `<!-- all -->` line ends its default part; the rest prints with --all.let (summary, details) = text.split_once("<!-- all -->").unwrap_or((text, ""));- print!("{}", help_text(summary));- if topic == "cameras" {print!("{PROGRAM_ENUMS}");}+ write!(out, "{}", help_text(summary)).map_err(crate::output::error)?;+ if topic == "cameras" {write!(out, "{PROGRAM_INPUTS}").map_err(crate::output::error)?;}if all {- print!("{}", help_text(details));- for line in topic_lines(topic) { println!("{line}"); }- if topic == "programs" { println!("\n```slang\n{}```", vork_render::program_help()); }+ write!(out, "{}", help_text(details)).map_err(crate::output::error)?;+ for line in topic_lines(topic) { writeln!(out, "{line}").map_err(crate::output::error)?; }+ if topic == "programs" { writeln!(out, "\n```slang\n{}```", vork_render::program_help()).map_err(crate::output::error)?; }}Ok(())}@@ -119,6 +148,28 @@ fn serve(topic: Option<&str>, field: Option<&str>, all: bool) -> Result<()> {mod tests {use super::*;#[test]+ fn camera_fields_and_heading_paths_resolve() {+ for name in ["lens", "sensor_width", "shift", "use_dof", "aperture_blades", "projection"] {+ assert_eq!(field_lines(&format!("std/camera.{name}")).len(), 1);+ }+ assert!(field_lines("camera.material")[0].contains("(camera)"));+ assert!(field_lines("camera.energy").is_empty());+ assert!(!field_lines("mesh.geometry").is_empty());+ }+ #[test]+ fn target_help_explains_structural_aim_animation() {+ assert!(field_lines("node.target")[0].contains("structural, not animatable"));+ let animation = document("animation").unwrap();+ assert!(animation.contains("including [x,y,z]"));+ assert!(animation.contains("[\"nodes\",\"aim\",\"translation\"]"));+ }+ #[test]+ fn png_alpha_is_documented() {+ let outputs = document("outputs").unwrap();+ assert!(outputs.contains(".png RGBA still (keeps alpha"));+ assert!(outputs.contains("render.background \"transparent\""));+ }+ #[test]fn every_supported_openpbr_input_has_exact_help() {use vork_scene::v2::{OpenPbrParam, OPENPBR};for p in OPENPBR {diff --git a/crates/vork-cli/src/init.rs b/crates/vork-cli/src/init.rsnew file mode 100644index 0000000..cd0f94c--- /dev/null+++ b/crates/vork-cli/src/init.rs@@ -0,0 +1,56 @@+//! One bundled scene, with optional ordinary authoring source. No network or GPU.+use anyhow::{Context, Result};+use clap::{Parser, ValueEnum};+use std::{fs, io::Write, path::PathBuf};++#[derive(Clone, Copy, ValueEnum)]+pub enum Language { Json, Typescript, Python }++#[derive(Parser)]+pub struct Args {+ /// Project directory (default: current directory). Existing unrelated files are preserved.+ #[arg(default_value = ".")]+ dir: PathBuf,+ /// Also write editable TypeScript or Python source; scene.json always renders immediately.+ #[arg(long, value_enum, default_value = "json")]+ language: Language,+}+impl Args {+ pub fn run(&self) -> Result<()> {+ self.create()+ }+ fn create(&self) -> Result<()> {+ let scene = include_str!("starter.json");+ let mut files = vec![("scene.json", scene.to_owned())];+ let author = match self.language {+ Language::Json => "Edit scene.json, then render again.\n".to_owned(),+ Language::Typescript => {+ files.push(("package.json", "{\n \"private\": true,\n \"type\": \"module\"\n}\n".to_owned()));+ let mut value: serde_json::Value = serde_json::from_str(scene)?;+ for (i, name) in ["blue", "coral", "floor"].iter().enumerate() { value["nodes"][i]["geometry"] = (*name).into(); }+ let literal = serde_json::to_string_pretty(&value)?;+ files.push(("scene.ts", format!("import {{ writeScene, sphere, box, grid, type Scene }} from '@voyager-so/vork';\n\nconst blue = sphere('blue', {{radius: 0.85, segments: 64, rings: 32}});\nconst coral = box('coral', {{size: [0.9, 0.9, 0.9]}});\nconst floor = grid('floor', {{size: [200, 200]}});\nconst scene = {{...{literal}, buffers: {{...blue.buffers, ...coral.buffers, ...floor.buffers}}, geometry: {{...blue.geometry, ...coral.geometry, ...floor.geometry}}}} satisfies Scene;\nawait writeScene(scene, 'scene.json');\n")));+ "Edit scene.ts, then run `node scene.ts` to rewrite scene.json. Requires Node 22.18+ and @voyager-so/vork installed in this project. Install the SDK bundled with vork using `npm install PREFIX/lib/vork/sdk`. Replace PREFIX with your vork installation prefix (default: ~/.local). For a source checkout use its packages/ts directory. See `vork help sdk`.\n".to_owned()+ }+ Language::Python => {+ let mut value: serde_json::Value = serde_json::from_str(scene)?;+ for (i, name) in ["blue", "coral", "floor"].iter().enumerate() { value["nodes"][i]["geometry"] = (*name).into(); }+ let literal = serde_json::to_string_pretty(&value)?;+ files.push(("scene.py", format!("from vork import std, write_scene\n\nscene = {literal}\nscene['buffers'] = {{}}\nscene['geometry'] = {{}}\nfor shape, options in [('sphere', {{'name': 'blue', 'radius': 0.85, 'segments': 64, 'rings': 32}}), ('box', {{'name': 'coral', 'size': [0.9, 0.9, 0.9]}}), ('grid', {{'name': 'floor', 'size': [200, 200]}})]:\n fragment = std(shape, options)\n scene['buffers'].update(fragment['buffers'])\n scene['geometry'].update(fragment['geometry'])\nwrite_scene(scene, 'scene.json')\n")));+ "Edit scene.py, then run `python scene.py` to rewrite scene.json. Requires Python 3.11+ and the vork SDK installed in your environment. In a virtual environment, install the SDK bundled with vork using `python -m pip install PREFIX/lib/vork/python`. Replace PREFIX with your vork installation prefix (default: ~/.local). For a source checkout use its packages/python directory. See `vork help sdk`.\n".to_owned()+ }+ };+ files.push(("README.md", format!("# Your first vork scene\n\n{author}\n```sh\nvork render scene.json --profile std/draft --out render.png\nvork help\n```\n\nOpen render.png. Try changing the colours, camera target or light positions.\nUse `--profile std/final` for a cleaner image. No fetched assets are needed.\nFor an npm project use `npx vork` in place of `vork`.\n")));+ fs::create_dir_all(&self.dir).with_context(|| format!("create {}", self.dir.display()))?;+ for (name, _) in &files {+ if self.dir.join(name).symlink_metadata().is_ok() {+ return Err(anyhow::anyhow!("{} already exists; choose another directory (no files overwritten)", self.dir.join(name).display()).context(vork_render::failure::FailureKind::Usage));+ }+ }+ for (name, content) in files {+ fs::OpenOptions::new().write(true).create_new(true).open(self.dir.join(name))?.write_all(content.as_bytes())?;+ }+ output!("Created {}\nNext: enter that directory, then run:\n vork render scene.json --profile std/draft --out render.png\n vork help\nRead README.md for authoring steps.", self.dir.display());+ Ok(())+ }+}diff --git a/crates/vork-cli/src/main.rs b/crates/vork-cli/src/main.rsindex 55f8751..1fb25ad 100644--- a/crates/vork-cli/src/main.rs+++ b/crates/vork-cli/src/main.rs@@ -1,6 +1,14 @@//! Unstable, internal: all Rust APIs in this crate are free to change.+// All command output is fallible; the process boundary treats a closed consumer as success.+macro_rules! output {+ ($($arg:tt)*) => { crate::output::line(format_args!($($arg)*))? };+}+mod output;+mod constants;+mod init;+mod progress;mod help;mod std_command;use anyhow::Result;@@ -23,6 +31,8 @@ struct Args {}#[derive(Subcommand)]enum Command {+ /// Create a small offline project ready to render.+ Init(init::Args),/// Warm default-profile shaders in this machine's driver cache.Setup {/// Also warm every bundled program/profile and built-in descriptor.@@ -95,6 +105,7 @@ fn channel(value: &str) -> Result<String, String> {fn main() -> std::process::ExitCode {match run() {Ok(()) => std::process::ExitCode::SUCCESS,+ Err(error) if output::broken_pipe(&error) => std::process::ExitCode::SUCCESS,Err(error) => {eprintln!("Error: {error:#}");if vork_render::failure::suggests_setup(&error) { eprintln!("Run `vork setup` for this machine’s GPU and tools report."); }@@ -105,7 +116,15 @@ fn main() -> std::process::ExitCode {fn run() -> Result<()> {let entry = std::time::SystemTime::now();let start = std::time::Instant::now();- let Args { command } = Args::parse();+ let Args { command } = match Args::try_parse() {+ Ok(args) => args,+ Err(error) => {+ let code = error.exit_code();+ if error.use_stderr() { error.print()?; }+ else { error.print().map_err(output::error)?; }+ std::process::exit(code);+ }+ };if matches!(command, Command::Render { diagnostics: true, .. }) {eprintln!("cli_entry_unix_ns: {}; cli_parse_ms: {:.3}",@@ -117,21 +136,44 @@ fn run() -> Result<()> {return vork_render::Renderer::prepare_release_shaders();}if let Command::Setup { all } = &command {+ output!("vork {}", env!("VORK_VERSION"));+ output!("OS: {} ({})", std::env::consts::OS, std::env::consts::ARCH);+ match std::process::Command::new("ffmpeg").arg("-version").output() {+ Ok(output) if output.status.success() => {+ if let Some(version) = String::from_utf8_lossy(&output.stdout).lines().next() {+ output!("FFmpeg version: {version}");+ }+ }+ _ => output!("FFmpeg version: unavailable"),+ }+ let progress = progress::Monitor::start("Setup: opening GPU and checking tools");let renderer=vork_render::Renderer::new().map_err(|error| {eprintln!("GPU: {error:#}. Install a supported GPU driver; in Docker enable GPU access with --gpus all.");+ eprintln!("Rendering requires an NVIDIA GPU with Vulkan ray queries, or Apple Silicon. Docker does not provide a GPU on its own. On your own NVIDIA Linux machine, use the Docker runtime: docs/REMOTE-GPU.md. Hosted rendering: details will be added when available. Scene authoring and `vork help` work without a GPU.");error.context(vork_render::failure::FailureKind::Device)})?;- renderer.setup_report()?;+ let device_s = start.elapsed().as_secs_f64();+ let tools_start = std::time::Instant::now();+ renderer.setup_report(&mut std::io::stdout().lock()).map_err(output::context)?;+ let tools_s = tools_start.elapsed().as_secs_f64();+ let warm_start = std::time::Instant::now();+ vork_slang::progress::phase("Setup: warming shaders and driver pipelines", 0);if *all { renderer.warm_shaders()?; } else { renderer.warm_startup_shaders()?; }- println!("Shader setup completed in {:.3} s",start.elapsed().as_secs_f64());+ progress.finish();+ output!("Setup phases: device {:.3} s; tools {:.3} s; shaders/cache {:.3} s", device_s, tools_s, warm_start.elapsed().as_secs_f64());+ output!("Shader setup completed in {:.3} s",start.elapsed().as_secs_f64());return Ok(());}if let Command::Help { topic, field, all } = &command {return help::run(topic.as_deref(), field.as_deref(), *all);}+ if let Command::Init(args) = &command {+ return args.run();+ }if let Command::Std(args) = &command {return args.run();}+ let progress = progress::Monitor::start("Render: loading scene and opening GPU");let diagnostics = matches!(command, Command::Render { diagnostics: true, .. });let (rendered, out) = match command {Command::Render {@@ -160,8 +202,9 @@ fn run() -> Result<()> {start.elapsed().as_secs_f64() * 1000.);}+ progress.finish();let report = &rendered.report;- println!(+ output!("Rendered {} frames in {:.3}s; outputs: {}",report["frames"],report["wall_ms"].as_f64().unwrap() / 1000.,@@ -170,15 +213,22 @@ fn run() -> Result<()> {.collect::<Vec<_>>().join(", "));+ if let Some(sidecars) = report["sidecars"].as_array().filter(|paths| !paths.is_empty()) {+ output!("Sidecars: {}", sidecars.iter().filter_map(|p| p.as_str()).collect::<Vec<_>>().join(", "));+ }let exposures = report["exposure"].as_array().map_or(&[][..], Vec::as_slice);for row in exposures {let line = exposure_line(&row["exposure"]);- if exposures.len() == 1 { println!("{line}"); } else { println!("{}: {line}", row["output"].as_str().unwrap_or_default()); }+ if exposures.len() == 1 { output!("{line}"); } else { output!("{}: {line}", row["output"].as_str().unwrap_or_default()); }+ }+ if let Some(warnings) = report["warnings"].as_array().filter(|warnings| !warnings.is_empty()) {+ eprintln!("\nWARNING: {} REQUESTED EFFECT(S) DROPPED: {}. Review the detailed warnings above and in render metadata before accepting this render.",+ warnings.len(), warnings.iter().filter_map(|warning| warning["code"].as_str()).collect::<Vec<_>>().join(", "));}// Shot::render has joined file writers, reaped input decoders, finished muxing, saved idle caches and// written reports. Keep GPU owners alive: process exit discards unused variants// and reclaims resources without driver teardown. Errors still unwind.- std::io::stdout().flush()?;+ std::io::stdout().flush().map_err(output::error)?;std::io::stderr().flush()?;// libc exit runs driver atexit hooks: CUDA/NVENC can block there when its// finished GPU owners are intentionally kept alive. Files and Rust streams arediff --git a/crates/vork-cli/src/output.rs b/crates/vork-cli/src/output.rsnew file mode 100644index 0000000..2f0e1cb--- /dev/null+++ b/crates/vork-cli/src/output.rs@@ -0,0 +1,31 @@+use std::io::Write;++#[derive(Debug)]+struct Stdout;+impl std::fmt::Display for Stdout {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("write stdout") }+}+impl std::error::Error for Stdout {}++pub fn context(error: anyhow::Error) -> anyhow::Error { error.context(Stdout) }+pub fn error(error: std::io::Error) -> anyhow::Error { context(error.into()) }++pub fn line(args: std::fmt::Arguments<'_>) -> anyhow::Result<()> {+ writeln!(std::io::stdout().lock(), "{args}").map_err(error)+}++pub fn broken_pipe(error: &anyhow::Error) -> bool {+ error.downcast_ref::<Stdout>().is_some() && error.chain().any(|cause| cause.downcast_ref::<std::io::Error>()+ .is_some_and(|error| error.kind() == std::io::ErrorKind::BrokenPipe))+}++#[cfg(test)]+mod tests {+ #[test]+ fn only_stdout_broken_pipes_are_clean_termination() {+ let pipe = || std::io::Error::from(std::io::ErrorKind::BrokenPipe);+ assert!(super::broken_pipe(&super::error(pipe())));+ assert!(!super::broken_pipe(&pipe().into()));+ assert!(!super::broken_pipe(&super::error(std::io::Error::from(std::io::ErrorKind::StorageFull))));+ }+}diff --git a/crates/vork-cli/src/progress.rs b/crates/vork-cli/src/progress.rsnew file mode 100644index 0000000..dc45383--- /dev/null+++ b/crates/vork-cli/src/progress.rs@@ -0,0 +1,56 @@+//! A single low-frequency observer for terminal and durable redirected progress.+use std::{io::Write, sync::mpsc, thread, time::{Duration, Instant}};+use vork_slang::progress;++pub struct Monitor {+ stop: mpsc::Sender<bool>,+ worker: Option<thread::JoinHandle<()>>,+}+fn line(start: Instant) -> String {+ let (s, done) = progress::snapshot();+ let mut line = format!("[{:.0}s] {}", start.elapsed().as_secs_f64(), s.phase);+ if s.total > 0 {+ line.push_str(&format!(" {done}/{} ({:.0}%)", s.total, 100. * done as f64 / s.total as f64));+ }+ let compiling = s.shaders_started > s.shaders_done || s.pipelines_started > s.pipelines_done;+ if (s.shaders_started > 0 || s.pipelines_started > 0) && (compiling || s.total == 0) {+ line.push_str(&format!("; shader jobs {}/{}; driver pipelines {}/{} complete (discovered so far)",+ s.shaders_done, s.shaders_started, s.pipelines_done, s.pipelines_started));+ }+ line+}+impl Monitor {+ pub fn start(phase: &'static str) -> Self {+ progress::enable(phase);+ let (stop, receive) = mpsc::channel();+ let start = Instant::now();+ // Print before spawning so even initialization is visibly underway.+ let _ = writeln!(std::io::stderr(), "{}", line(start));+ let worker = thread::spawn(move || {+ let interval = Duration::from_secs(5);+ loop {+ let finished = match receive.recv_timeout(interval) {+ Ok(success) => Some(success),+ Err(mpsc::RecvTimeoutError::Disconnected) => Some(false),+ Err(mpsc::RecvTimeoutError::Timeout) => None,+ };+ let mut stderr = std::io::stderr().lock();+ let suffix = if let Some(success) = finished {+ if success { "; done" } else { "; failed" }+ } else { "" };+ let _ = writeln!(stderr, "{}{suffix}", line(start));+ let _ = stderr.flush();+ if finished.is_some() { break; }+ }+ });+ Self { stop, worker: Some(worker) }+ }+ pub fn finish(mut self) { self.join(true); }+ fn join(&mut self, success: bool) {+ if let Some(worker) = self.worker.take() {+ let _ = self.stop.send(success);+ let _ = worker.join();+ }+ }+}+impl Drop for Monitor { fn drop(&mut self) { self.join(false); } }diff --git a/crates/vork-cli/src/starter.json b/crates/vork-cli/src/starter.jsonnew file mode 100644index 0000000..aaddade--- /dev/null+++ b/crates/vork-cli/src/starter.json@@ -0,0 +1,13 @@+{+ "$schema": "https://voyager.so/vork/schema/scene.schema.json",+ "version": 2,+ "nodes": [+ {"type":"mesh","name":"blue","translation":[-0.65,0.85,0],"geometry":{"std":"sphere","radius":0.85,"segments":64,"rings":32},"materials":[{"inputs":{"base_color":[0.025,0.27,0.38],"specular_roughness":0.24,"coat_weight":0.3}}]},+ {"type":"mesh","name":"coral","translation":[0.9,0.45,0.35],"rotation":{"euler":[0,0.28,0]},"geometry":{"std":"box","size":[0.9,0.9,0.9]},"materials":[{"inputs":{"base_color":[0.8,0.16,0.075],"specular_roughness":0.35}}]},+ {"type":"mesh","name":"floor","geometry":{"std":"grid","size":[200,200]},"materials":[{"inputs":{"base_color":[0.38,0.31,0.23],"specular_roughness":0.7}}]},+ {"type":"light","shape":"rectangle","translation":[-3,5,4],"target":[0,0.5,0],"energy":1100,"size":4,"color":[1,0.88,0.72]},+ {"type":"light","shape":"rectangle","translation":[3,3,-2],"target":[0,0.5,0],"energy":900,"size":3,"color":[0.65,0.8,1]},+ {"type":"camera","translation":[3.4,2.6,5.8],"target":[0,0.7,0]}+ ],+ "render":{"resolution":[800,600],"duration":1}+}diff --git a/crates/vork-cli/src/std_command.rs b/crates/vork-cli/src/std_command.rsindex 34065a3..cc81fa3 100644--- a/crates/vork-cli/src/std_command.rs+++ b/crates/vork-cli/src/std_command.rs@@ -33,7 +33,7 @@ impl Args {vork_std::environment::prepare_frames(&argument,×,|time|source.frame(time,fps,u32::MAX),read,write)?} else {vork_std::environment::prepare(&argument,read,write)?}} else {vork_std::evaluate(&self.function,&argument)?};- println!("{result}");+ output!("{result}");Ok(())}}diff --git a/crates/vork-cli/tests/help.rs b/crates/vork-cli/tests/help.rsindex 10d26bb..e99f940 100644--- a/crates/vork-cli/tests/help.rs+++ b/crates/vork-cli/tests/help.rs@@ -50,7 +50,7 @@ fn help_routes_concepts_fields_and_diagnostics_without_losing_the_schema() {assert!(!root.contains("rejects unsafe profile clearance"));assert!(!root.contains("round shapes use Y as axis"));// Deep library signatures and inputs remain one --all away.- for (library, detail) in [("std", "std.procedurals: noise"), ("blender", "blender/filmic look:"), ("post", "streaks_angle")] {+ for (library, detail) in [("std", "std.procedurals: noise"), ("blender", "blender/filmic look:"), ("post", "source white to D65")] {assert!(!help(library).contains(detail), "{library} default shows {detail}");assert!(help_args(&[library, "--all"]).contains(detail), "{library} --all lost {detail}");}@@ -59,7 +59,7 @@ fn help_routes_concepts_fields_and_diagnostics_without_losing_the_schema() {for removed in ["absorption_color", "blender.volume", "blender/principled_volume"] {assert!(!blender_all.contains(removed), "blender --all advertises removed media: {removed}");}- assert!(std_all.contains("scatter: {on_geometry"));+ assert!(!std_all.contains("scatter:"));// Common builders stay on root; specialist signatures remain in std --all.assert!(root.contains("sphere: {name?:string") && root.contains("Std builders return {buffers,geometry}"));assert!(std_all.contains("rounded_box:"));@@ -249,3 +249,41 @@ fn camera_enum_tokens_come_from_program_reflection() {}}}++#[test]+fn help_closed_pipe_exits_successfully() {+ use std::process::{Command, Stdio};+ let mut child = Command::new(env!("CARGO_BIN_EXE_vork"))+ .args(["help", "std", "--all"])+ .stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();+ drop(child.stdout.take());+ let output = child.wait_with_output().unwrap();+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));+ assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr));+}++#[test]+fn optics_and_compositor_programs_are_directly_findable() {+ let camera = help("std/camera");+ assert!(camera.contains("std/camera.lens: number; mm; default 50"));+ assert!(camera.contains("std/camera.shift: vec2; default [0,0]"));+ for name in ["lens", "sensor_width", "ortho_scale", "shift", "clip_start", "use_dof", "aperture_ratio"] {+ let line = format!("std/camera.{name}:");+ assert!(camera.contains(&line), "{line}");+ assert!(help_args(&["field", &format!("std/camera.{name}")]).contains(&line));+ }+ assert!(help_args(&["field", "camera.material"]).contains("node.material (camera)"));+ let bloom = help("std/bloom");+ for contract in ["prepare: requires original", "combine: requires original and source", "{channel:color}"] {+ assert!(bloom.contains(contract), "{contract}");+ }+ assert!(!help("post").contains("post/glare"));+}++#[cfg(target_os = "linux")]+#[test]+fn stdout_filesystem_failure_keeps_io_category() {+ let output = Command::new(env!("CARGO_BIN_EXE_vork")).arg("help")+ .stdout(std::fs::File::options().write(true).open("/dev/full").unwrap()).output().unwrap();+ assert_eq!(output.status.code(), Some(5), "{output:?}");+}diff --git a/crates/vork-cli/tests/init.rs b/crates/vork-cli/tests/init.rsnew file mode 100644index 0000000..fa7b4b9--- /dev/null+++ b/crates/vork-cli/tests/init.rs@@ -0,0 +1,97 @@+use std::{fs, process::Command};+fn run(dir: &std::path::Path, args: &[&str]) -> std::process::Output {+ Command::new(env!("CARGO_BIN_EXE_vork")).current_dir(dir).args(args).output().unwrap()+}+#[test]+fn offline_starter_and_authoring_variants_preserve_user_files() {+ let root = std::env::temp_dir().join(format!("vork-init-{}", std::process::id()));+ fs::create_dir_all(&root).unwrap();+ for language in ["json", "typescript", "python"] {+ let output = run(&root, &["init", language, "--language", language]);+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));+ let project = root.join(language);+ let scene: serde_json::Value = serde_json::from_slice(&fs::read(project.join("scene.json")).unwrap()).unwrap();+ assert_eq!(scene["version"], 2);+ assert_eq!(scene["$schema"], "https://voyager.so/vork/schema/scene.schema.json");+ assert_eq!(scene["nodes"].as_array().unwrap().len(), 6);+ assert!(fs::read_to_string(project.join("README.md")).unwrap().contains("vork help"));+ assert!(!project.join("AGENTS.md").exists());+ if language == "typescript" {+ let package: serde_json::Value = serde_json::from_slice(&fs::read(project.join("package.json")).unwrap()).unwrap();+ assert_eq!(package["type"], "module");+ assert!(fs::read_to_string(project.join("README.md")).unwrap().contains("npm install PREFIX/lib/vork/sdk"));+ }+ if language == "python" {+ assert!(fs::read_to_string(project.join("README.md")).unwrap().contains("python -m pip install PREFIX/lib/vork/python"));+ }+ fs::write(project.join("scene.json"), "user work").unwrap();+ let again = run(&project, &["init"]);+ assert_eq!(again.status.code(), Some(2));+ assert_eq!(fs::read_to_string(project.join("scene.json")).unwrap(), "user work");+ }+ let conflict = root.join("conflict");+ fs::create_dir(&conflict).unwrap();+ fs::write(conflict.join("README.md"), "notes").unwrap();+ assert!(!run(&conflict, &["init"]).status.success());+ assert!(!conflict.join("scene.json").exists());+ let empty = root.join("current");+ fs::create_dir(&empty).unwrap();+ assert!(run(&empty, &["init"]).status.success());+ assert!(!run(&root, &["init", "invalid", "--language", "rust"]).status.success());+ assert!(!root.join("invalid").exists());+ fs::remove_dir_all(root).unwrap();+}++#[test]+fn filesystem_failure_is_not_an_argument_refusal() {+ let root = std::env::temp_dir().join(format!("vork-init-file-parent-{}", std::process::id()));+ fs::write(&root, "file, not directory").unwrap();+ let output = Command::new(env!("CARGO_BIN_EXE_vork")).arg("init").arg(root.join("child")).output().unwrap();+ assert_eq!(output.status.code(), Some(5), "{output:?}");+ fs::remove_file(root).unwrap();+}++#[cfg(unix)]+#[test]+fn denied_parent_is_a_filesystem_error() {+ use std::os::unix::fs::PermissionsExt;+ let root = std::env::temp_dir().join(format!("vork-init-denied-{}", std::process::id()));+ fs::create_dir(&root).unwrap();+ fs::set_permissions(&root, fs::Permissions::from_mode(0o500)).unwrap();+ if fs::create_dir(root.join("probe")).is_ok() {+ // Privileged test runners can bypass mode bits.+ fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();+ fs::remove_dir_all(&root).unwrap();+ return;+ }+ let output = Command::new(env!("CARGO_BIN_EXE_vork")).arg("init").arg(root.join("child")).output().unwrap();+ fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();+ fs::remove_dir_all(&root).unwrap();+ assert_eq!(output.status.code(), Some(5), "{output:?}");+}++#[test]+fn help_init_and_usage_errors() {+ let dir = std::env::temp_dir();+ for args in [vec!["help", "init"], vec!["help", "init", "--all"]] {+ let output = run(&dir, &args);+ assert!(output.status.success());+ assert!(String::from_utf8_lossy(&output.stdout).contains("vork init"));+ }+ for args in [vec!["help", "missing-topic"], vec!["help", "field"], vec!["help", "field", "missing.field"], vec!["help", "init", "extra"]] {+ let output = run(&dir, &args);+ assert_eq!(output.status.code(), Some(2));+ assert!(!String::from_utf8_lossy(&output.stderr).contains("write stdout"));+ }+}++#[test]+fn typescript_package_conflict_preserves_project() {+ let root = std::env::temp_dir().join(format!("vork-init-package-{}", std::process::id()));+ fs::create_dir_all(&root).unwrap();+ fs::write(root.join("package.json"), "user package").unwrap();+ assert_eq!(run(&root, &["init", "--language", "typescript"]).status.code(), Some(2));+ assert_eq!(fs::read_to_string(root.join("package.json")).unwrap(), "user package");+ assert!(!root.join("scene.json").exists());+ fs::remove_dir_all(root).unwrap();+}diff --git a/crates/vork-cli/tests/invalid_scene.rs b/crates/vork-cli/tests/invalid_scene.rsindex a9c1e79..a0908d6 100644--- a/crates/vork-cli/tests/invalid_scene.rs+++ b/crates/vork-cli/tests/invalid_scene.rs@@ -25,24 +25,27 @@ fn invalid_scene_exits_with_validation_error() {.unwrap(),).unwrap();+ // Drain diagnostics to a file while polling: a pipe can fill before exit,+ // making the harness itself look like a renderer shutdown deadlock.+ let log = dir.join("stderr.log");for _ in 0..32 {let mut child = Command::new(env!("CARGO_BIN_EXE_vork")).arg("render").arg(&scene).arg("--out").arg(dir.join("frame.png"))- .stdout(Stdio::piped())- .stderr(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(std::fs::File::create(&log).unwrap()).spawn().unwrap();let start = Instant::now();while child.try_wait().unwrap().is_none() {if start.elapsed() > Duration::from_secs(30) {child.kill().unwrap();- let output = child.wait_with_output().unwrap();+ child.wait().unwrap();panic!("scene error hung during shutdown: {}",- String::from_utf8_lossy(&output.stderr)+ std::fs::read_to_string(&log).unwrap());}std::thread::sleep(Duration::from_millis(10));@@ -53,9 +56,9 @@ fn invalid_scene_exits_with_validation_error() {Some(3),"status: {}; stderr: {}",output.status,- String::from_utf8_lossy(&output.stderr)+ std::fs::read_to_string(&log).unwrap());- let stderr = String::from_utf8_lossy(&output.stderr);+ let stderr = std::fs::read_to_string(&log).unwrap();assert!(stderr.contains("unknown field \"mesh\""), "{stderr}");assert!(!dir.join("frame.png").exists());}diff --git a/crates/vork-cli/tests/output_patterns.rs b/crates/vork-cli/tests/output_patterns.rsindex fe9d66e..83efa64 100644--- a/crates/vork-cli/tests/output_patterns.rs+++ b/crates/vork-cli/tests/output_patterns.rs@@ -20,6 +20,7 @@ fn png_frame_patterns_are_usage_errors_even_for_one_still() {}#[test]+#[ignore = "renders images; requires a supported GPU, pinned Slang and OIDN"]fn png_still_paths_preserve_literal_characters() {let dir = std::env::temp_dir().join(format!("vork-literal-output-{}", std::process::id()));std::fs::create_dir_all(&dir).unwrap();diff --git a/crates/vork-cli/tests/range_diagnostics.rs b/crates/vork-cli/tests/range_diagnostics.rsindex 33c6227..bac44d5 100644--- a/crates/vork-cli/tests/range_diagnostics.rs+++ b/crates/vork-cli/tests/range_diagnostics.rs@@ -1,6 +1,7 @@use std::process::Command;#[test]+#[ignore = "renders images; requires a supported GPU, pinned Slang and OIDN"]fn implicit_still_notice_requires_written_output() {let dir = std::env::temp_dir().join(format!("vork-range-diagnostics-{}", std::process::id()));std::fs::create_dir_all(&dir).unwrap();@@ -10,7 +11,7 @@ fn implicit_still_notice_requires_written_output() {let _ = std::fs::remove_file(&image);std::fs::write(&scene, serde_json::json!({"version":2,"nodes":[{"type":"camera","name":"cam"}],- "materials":{"glow":{"program":"post/glare","inputs":{"size":size}}},+ "materials":{"glow":{"program":{"file":concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/compositor-effects/glare.slang")},"inputs":{"size":size}}},"render":{"duration":1,"resolution":[8,8],"compositor":["glow"]}}).to_string()).unwrap();let mut command = Command::new(env!("CARGO_BIN_EXE_vork"));@@ -22,7 +23,7 @@ fn implicit_still_notice_requires_written_output() {assert_eq!(image.exists(), size != 6, "{stderr}");assert_eq!(stderr.contains("rendered t=0"), size != 6 && !explicit, "{stderr}");if size == 6 {- for expected in ["render.compositor[0]", "glow", "post/glare", "received 6", "[0, 1]"] {+ for expected in ["render.compositor[0]", "glow", "received 6", "[0, 1]"] {assert!(stderr.contains(expected), "missing {expected}: {stderr}");}}@@ -31,25 +32,33 @@ fn implicit_still_notice_requires_written_output() {}#[test]-fn duplicate_environments_identify_nodes_in_every_profile() {+#[ignore = "renders images; requires a real GPU, pinned Slang and OIDN"]+fn duplicate_environments_warn_render_and_return_authored_requests() {let dir = std::env::temp_dir().join(format!("vork-environment-diagnostics-{}", std::process::id()));std::fs::create_dir_all(&dir).unwrap();let scene = dir.join("scene.json");std::fs::write(&scene, serde_json::json!({"version":2,"nodes":[{"type":"camera"},{"type":"light","shape":"environment","name":"world_a"},- {"type":"node","children":[{"type":"light","shape":"environment","name":"world_b","energy":0}]}- ]}).to_string()).unwrap();+ {"type":"node","children":[{"type":"light","shape":"environment","name":"world_b","energy":2}]}+ ],"render":{"resolution":[8,8]}}).to_string()).unwrap();for profile in ["std/draft", "std/final", "std/path"] {+ let image = dir.join("still.png");let output = Command::new(env!("CARGO_BIN_EXE_vork"))- .arg("render").arg(&scene).args(["--profile", profile, "--out"])- .arg(dir.join("still.png")).output().unwrap();+ .arg("render").arg(&scene).args(["--profile", profile, "--set", "samples=1", "--set", "denoise=false", "--out"])+ .arg(&image).output().unwrap();let stderr = String::from_utf8_lossy(&output.stderr);- assert!(!output.status.success(), "{stderr}");- for expected in ["only one environment", "world_a", "world_b"] {+ assert!(output.status.success(), "{stderr}");+ for expected in ["WARNING: REQUESTED EFFECT DROPPED", "world_a", "world_b", "additional_environment"] {assert!(stderr.contains(expected), "{profile}: {stderr}");}- assert!(!stderr.contains("raster renderer"), "{stderr}");+ assert!(image.exists());+ let metadata: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("still.png.meta.json")).unwrap()).unwrap();+ let warnings = metadata["warnings"].as_array().unwrap();+ assert_eq!(warnings.len(), 1, "{warnings:?}");+ assert_eq!(warnings[0]["code"], "additional_environment");+ assert_eq!(warnings[0]["requested"]["node"]["name"], "world_b");+ assert_eq!(warnings[0]["requested"]["node"]["energy"].as_f64(), Some(2.));}std::fs::remove_dir_all(dir).unwrap();}diff --git a/crates/vork-cli/tests/stdout.rs b/crates/vork-cli/tests/stdout.rsnew file mode 100644index 0000000..03987d0--- /dev/null+++ b/crates/vork-cli/tests/stdout.rs@@ -0,0 +1,80 @@+use std::process::{Command, Stdio};++#[test]+fn closed_consumers_terminate_successfully_without_panics() {+ let root = std::env::temp_dir().join(format!("vork-stdout-init-{}", std::process::id()));+ let project = root.to_str().unwrap();+ for args in [vec!["std", "sphere", "{}"], vec!["help", "programs", "--all"],+ vec!["init", project], vec!["setup"], vec!["--help"], vec!["--version"]] {+ let mut child = Command::new(env!("CARGO_BIN_EXE_vork")).args(&args)+ .stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();+ drop(child.stdout.take());+ let output = child.wait_with_output().unwrap();+ assert!(output.status.success(), "{args:?}: {output:?}");+ assert!(output.stderr.is_empty(), "{args:?}: {output:?}");+ }+ std::fs::remove_dir_all(root).unwrap();+}++#[cfg(target_os = "linux")]+#[test]+fn real_stdout_errors_are_filesystem_failures() {+ let root = std::env::temp_dir().join(format!("vork-full-init-{}", std::process::id()));+ for args in [vec!["std", "sphere", "{}"], vec!["help"],+ vec!["init", root.to_str().unwrap()], vec!["setup"], vec!["--help"], vec!["--version"]] {+ let output = Command::new(env!("CARGO_BIN_EXE_vork")).args(&args)+ .stdout(std::fs::File::options().write(true).open("/dev/full").unwrap()).output().unwrap();+ assert_eq!(output.status.code(), Some(5), "{args:?}: {output:?}");+ assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");+ }+ std::fs::remove_dir_all(root).unwrap();+}++#[test]+fn consumer_can_close_after_reading_a_prefix() {+ use std::io::Read;+ let mut child = Command::new(env!("CARGO_BIN_EXE_vork")).args(["std", "sphere", "{}"])+ .stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();+ let mut stdout = child.stdout.take().unwrap();+ stdout.read_exact(&mut [0u8; 1]).unwrap();+ drop(stdout);+ let output = child.wait_with_output().unwrap();+ assert!(output.status.success(), "{output:?}");+ assert!(output.stderr.is_empty(), "{output:?}");+}++#[test]+fn gpu_status_output_uses_the_same_stdout_policy() {+ if std::env::var("VORK_GPU_TESTS").as_deref() != Ok("1") {+ eprintln!("SKIP GPU stdout test: set VORK_GPU_TESTS=1 on a supported GPU");+ return;+ }+ use std::io::{BufRead, BufReader};+ let mut setup = Command::new(env!("CARGO_BIN_EXE_vork")).arg("setup")+ .stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();+ let mut headers = BufReader::new(setup.stdout.take().unwrap());+ // CLI version, OS and FFmpeg precede the renderer's setup report.+ for _ in 0..3 { assert!(headers.read_line(&mut String::new()).unwrap() > 0); }+ drop(headers);+ let output = setup.wait_with_output().unwrap();+ assert!(output.status.success(), "{output:?}");+ assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");++ let root = std::env::temp_dir().join(format!("vork-gpu-stdout-{}", std::process::id()));+ std::fs::create_dir_all(&root).unwrap();+ let scene = root.join("scene.json");+ std::fs::write(&scene, r#"{"version":2,"nodes":[{"type":"camera"}],"render":{"resolution":[1,1]}}"#).unwrap();+ for full in [false, true] {+ if full && !cfg!(target_os = "linux") { continue; }+ let stdout = if full { Stdio::from(std::fs::File::options().write(true).open("/dev/full").unwrap()) }+ else { Stdio::piped() };+ let mut child = Command::new(env!("CARGO_BIN_EXE_vork")).arg("render").arg(&scene)+ .args(["--profile", "std/draft", "--set", "denoise=false", "--set", "samples=1", "--out"])+ .arg(root.join("frame.png")).stdout(stdout).stderr(Stdio::piped()).spawn().unwrap();+ drop(child.stdout.take());+ let output = child.wait_with_output().unwrap();+ assert_eq!(output.status.code(), Some(if full {5} else {0}), "{output:?}");+ assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");+ }+ std::fs::remove_dir_all(root).unwrap();+}diff --git a/crates/vork-encode/src/constants.rs b/crates/vork-encode/src/constants.rsindex b8bcf59..4caaf61 100644--- a/crates/vork-encode/src/constants.rs+++ b/crates/vork-encode/src/constants.rs@@ -1,7 +1,6 @@/// derived: wgpu COPY_BYTES_PER_ROW_ALIGNMENT, required by texture-to-buffer copies.pub(crate) const COPY_ROW_ALIGNMENT: u64 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64;/// quality/performance setting: caps the existing NVENC capability probe dimensions.-#[cfg(any(target_os = "linux", windows))]pub(crate) const NVENC_PROBE_EXTENT: u32 = 256;/// quality/performance setting: existing portable H.264 encoding speed preset.pub(crate) const SOFTWARE_PRESET: &str = "veryfast";diff --git a/crates/vork-encode/src/lib.rs b/crates/vork-encode/src/lib.rsindex 9c707a9..5a86048 100644--- a/crates/vork-encode/src/lib.rs+++ b/crates/vork-encode/src/lib.rs@@ -201,6 +201,7 @@ impl PreparedEncoder {ring_depth,) {Ok(session) => {+ eprintln!("Video encoder: native NVENC (GPU); FFmpeg muxing");return Ok(Encoder {gpu,width,@@ -245,46 +246,19 @@ impl PreparedEncoder {// Windows has no zero-copy session; ffmpeg's NVENC still beats libx264 after readback.#[cfg(any(target_os = "linux", windows))]if !prores && !matches!(gpu.backend, Backend::Readback) {- // Probe actual encoder initialization, not merely ffmpeg's compiled encoder list.- let available = Command::new("ffmpeg")- .args([- "-v",- "error",- "-f",- "lavfi",- "-i",- // Modern H.264 NVENC rejects 64x64; keep genuinely small- // outputs small so Auto can still select software for them.- &format!(- "color=size={}x{}",- width.min(NVENC_PROBE_EXTENT),- height.min(NVENC_PROBE_EXTENT)- ),- "-frames:v",- "1",- "-c:v",- "h264_nvenc",- "-f",- "null",- "-",- ])- .stdout(Stdio::null())- .stderr(Stdio::null())- .status()- .is_ok_and(|s| s.success());- if available {- codec = "h264_nvenc";- } else {- ensure!(- !matches!(gpu.backend, Backend::HardwareReadback),- "NVENC unavailable"- );+ match probe_ffmpeg_nvenc(width, height) {+ Ok(()) => codec = "h264_nvenc",+ Err(error) => {+ ensure!(!matches!(gpu.backend, Backend::HardwareReadback), "{error:#}");+ eprintln!("FFmpeg NVENC unavailable; using software libx264: {error:#}");+ }}}if prores {codec = "prores_ks";}require_ffmpeg_encoder(codec)?;+ eprintln!("Video encoder: FFmpeg {codec} (readback)");let mut command = Command::new("ffmpeg");command.args(["-v",@@ -397,8 +371,22 @@ impl PreparedEncoder {})}}-// Check before opening the rawvideo pipe: a missing codec otherwise surfaces as-// a platform-specific broken pipe on the first frame, hiding the actionable cause.+/// Test FFmpeg's NVENC against the installed driver, using the same initialization+/// probe for setup and output selection. Native Linux NVENC has a separate ABI.+pub fn probe_ffmpeg_nvenc(width: u32, height: u32) -> Result<()> {+ // Modern NVENC rejects tiny frames; preserve small output dimensions so Auto+ // can select software for those outputs rather than accepting a larger probe.+ let output = Command::new("ffmpeg")+ .args(["-v", "error", "-nostdin", "-f", "lavfi", "-i",+ &format!("color=size={}x{}", width.min(NVENC_PROBE_EXTENT), height.min(NVENC_PROBE_EXTENT)),+ "-frames:v", "1", "-c:v", "h264_nvenc", "-f", "null", "-"])+ .stdin(Stdio::null()).output().context("start FFmpeg NVENC probe")?;+ ensure!(output.status.success(), "FFmpeg h264_nvenc initialization failed ({}): {}",+ output.status, String::from_utf8_lossy(&output.stderr).trim());+ Ok(())+}++// Check before opening the rawvideo pipe so codec errors retain their cause.fn require_ffmpeg_encoder(codec: &str) -> Result<()> {let output = Command::new("ffmpeg").args(["-hide_banner", "-encoders"])diff --git a/crates/vork-encode/tests/nvenc_probe.rs b/crates/vork-encode/tests/nvenc_probe.rsnew file mode 100644index 0000000..fca29ae--- /dev/null+++ b/crates/vork-encode/tests/nvenc_probe.rs@@ -0,0 +1,25 @@+//! A compiled-in encoder can still be incompatible with the installed driver.+#![cfg(unix)]+use std::{os::unix::fs::PermissionsExt, process::Command};++#[test]+fn nvenc_probe_preserves_driver_diagnosis() {+ const CHILD: &str = "VORK_TEST_NVENC_PROBE";+ if std::env::var_os(CHILD).is_some() {+ let error = vork_encode::probe_ffmpeg_nvenc(1920, 1080).unwrap_err();+ let message = format!("{error:#}");+ assert!(message.contains("Driver does not support the required nvenc API version"), "{message}");+ assert!(message.contains("Required: 13.0 Found: 12.2"), "{message}");+ return;+ }+ let root = std::env::temp_dir().join(format!("vork-probe-{}", std::process::id()));+ std::fs::create_dir_all(&root).unwrap();+ let ffmpeg = root.join("ffmpeg");+ std::fs::write(&ffmpeg, b"#!/bin/sh\nprintf '%s\\n' 'Driver does not support the required nvenc API version. Required: 13.0 Found: 12.2' >&2\nexit 1\n").unwrap();+ std::fs::set_permissions(&ffmpeg, std::fs::Permissions::from_mode(0o755)).unwrap();+ let result = Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "nvenc_probe_preserves_driver_diagnosis", "--nocapture"])+ .env(CHILD, "1").env("PATH", &root).output().unwrap();+ std::fs::remove_dir_all(root).unwrap();+ assert!(result.status.success(), "{}\n{}", String::from_utf8_lossy(&result.stdout), String::from_utf8_lossy(&result.stderr));+}diff --git a/crates/vork-render/build.rs b/crates/vork-render/build.rsindex 2025c0a..364ff0e 100644--- a/crates/vork-render/build.rs+++ b/crates/vork-render/build.rs@@ -30,11 +30,11 @@ fn hash_tree(path: &Path, hash: &mut blake3::Hasher) {}}fn main() {- // The private corpus and its test modules are intentionally absent from public exports.+ // Explicit opt-in: directory layout must not change test admission.println!("cargo:rustc-check-cfg=cfg(vork_private_tests)");println!("cargo:rerun-if-changed=build.rs");- if std::path::Path::new("../../scenes").is_dir() {- println!("cargo:rerun-if-changed=../../scenes");+ println!("cargo:rerun-if-env-changed=VORK_PRIVATE_TESTS");+ if std::env::var("VORK_PRIVATE_TESTS").as_deref() == Ok("1") {println!("cargo:rustc-cfg=vork_private_tests");}// Texture bytes depend on codecs, not unrelated rendering changes or GPU IDs.@@ -93,6 +93,7 @@ fn main() {closure.as_str(),"build_slang.rs","src/slang_forward.rs",+ "src/programs.rs","src/forward_variant.rs","src/surface_native.rs","src/visibility_native.rs",diff --git a/crates/vork-render/shaders/bsdf.slang b/crates/vork-render/shaders/bsdf.slangindex 6be52c5..7a0d259 100644--- a/crates/vork-render/shaders/bsdf.slang+++ b/crates/vork-render/shaders/bsdf.slang@@ -357,6 +357,11 @@ bool transport_null_boundary(Closure c,float incident_ior) {if(c.geometry_thin_walled) return !transport_rough_transmission(c);return incident_ior==1. && c.specular_ior==1. && (c.transmission_depth<=0. || all(c.transmission_color==float3(1.)));}+// A null event preserves the preceding scattering vertex and its source MIS.+// It cannot also own a new finite-source endpoint at this interface.+bool transport_null_event(Closure c,float incident_ior,BsdfSample sample) {+ return transport_null_boundary(c,incident_ior) && sample.event==REG_RAY_TRANSMISSION && sample.pdf==0.;+}float3 transport_null_transmittance(Closure c,float3 view,float incident_ior,float3 smooth_normal,float3 geometric) {c=dielectric_interface(c,incident_ior,c.specular_ior);if(!transport_null_boundary(c,incident_ior)) return float3(0.);diff --git a/crates/vork-render/shaders/decoupled.slang b/crates/vork-render/shaders/decoupled.slangindex 0289c23..e5b9fbd 100644--- a/crates/vork-render/shaders/decoupled.slang+++ b/crates/vork-render/shaders/decoupled.slang@@ -1590,7 +1590,7 @@ void indirect_material<V:IVariant,P:IProgram>(uint3 gid) {let deferred_lit=P.lit && evaluation_allocator[first+7u]!=0u;if(!deferred_lit && all(response==float3(0.)) && all(scattering_response==float3(0.))) {return;}#ifdef VORK_DIFFUSE_MEDIUM- let ray_batch=REG_MEDIUM_GI_RAY_BATCH;+ let ray_batch=REG_GI_RAY_BATCH;#elselet ray_batch=32u;#endifdiff --git a/crates/vork-render/shaders/deform.slang b/crates/vork-render/shaders/deform.slangindex fea66d4..0b55b6e 100644--- a/crates/vork-render/shaders/deform.slang+++ b/crates/vork-render/shaders/deform.slang@@ -70,7 +70,12 @@ PoseVertex evaluate_vertex(uint i, uint pose, float4 header) {let determinant = dot(linear[0], cross(linear[1], linear[2]));// A collapsed skin still feeds displacement preparation while hidden.// Its normal has no inverse frame; retain the finite authored/morphed normal.- if (determinant!=0.) {n = normalize(mul(n, cofactor) * sign(determinant));}+ if (determinant!=0.) {+ let transformed=mul(n,cofactor)*sign(determinant);+ let scale=max(abs(transformed.x),max(abs(transformed.y),abs(transformed.z)));+ // Zero morph/leaf-tip normals remain finite until the surface's face fallback.+ n=all(isfinite(transformed)) && scale>0. ? normalize(transformed/scale) : float3(0.);+ }tangent = mul(tangent, linear);PoseVertex result;result.position=p; result.normal=n; result.tangent=float4(tangent,bind_tangent.w * sign(determinant));diff --git a/crates/vork-render/shaders/denoise.slang b/crates/vork-render/shaders/denoise.slangindex e41ba06..7810625 100644--- a/crates/vork-render/shaders/denoise.slang+++ b/crates/vork-render/shaders/denoise.slang@@ -1,6 +1,6 @@// Shared OIDN workspace: three float4 planes (RGB image stride 16).import vork_constants;-struct Params { uint count; uint samples; uint guide_alpha; uint width; uint spectral; uint channel; };+struct Params { uint count; uint samples; uint guide_alpha; uint width; uint spectral; uint channel; float input_scale; };[[vk::binding(0,0)]] ConstantBuffer<Params> params : register(b0);[[vk::binding(1,0)]] RWStructuredBuffer<float4> accumulation : register(u1);[[vk::binding(2,0)]] StructuredBuffer<float4> guides : register(t2);@@ -33,6 +33,7 @@ void pack(uint3 id : SV_DispatchThreadID) {shared[i].rgb=float3(shared[i][params.channel]);shared[params.count+i].rgb=float3(shared[params.count+i][params.channel]);}+ shared[i].rgb*=params.input_scale;float3 n=coverage>0. ? guides[2*i+1].rgb/coverage : float3(0.);// Accumulate unit normals, then retain the anti-aliased average length.if(params.channel==0u) shared[2*params.count+i]=float4(n,0.);@@ -45,10 +46,10 @@ void unpack(uint3 id : SV_DispatchThreadID) {uint i=id.y*params.width+id.x; if(i>=params.count) return;float4 p=accumulation[i]/float(params.samples);if(params.spectral!=0u) {- output[i][params.channel]=(shared[i].r+shared[i].g+shared[i].b)/3.;+ output[i][params.channel]=(shared[i].r+shared[i].g+shared[i].b)/(3.*params.input_scale);if(params.channel<2u) return;if(guides[2*i].a>0.) p.rgb=spectral_color(output[i].rgb,true)*p.a;- } else if(guides[2*i].a>0.) p.rgb=shared[i].rgb*p.a;+ } else if(guides[2*i].a>0.) p.rgb=(shared[i].rgb/params.input_scale)*p.a;output[i]=p;accumulation[i]=p*float(params.samples);}diff --git a/crates/vork-render/shaders/displacement.slangh b/crates/vork-render/shaders/displacement.slanghindex 1d94451..a8e5bca 100644--- a/crates/vork-render/shaders/displacement.slangh+++ b/crates/vork-render/shaders/displacement.slangh@@ -2,8 +2,9 @@import vork_constants;import material;import displacement_dispatch;-struct Evaluation { uint count; uint material; float time; float previous_time; uint point_vertices; uint pose; uint dispatch_width; uint deforming; uint4 object_header; float4x4 to_stream; float4x4 from_stream; };-[[vk::binding(0,2)]] ConstantBuffer<Evaluation> evaluation : register(b5);+struct Evaluation { uint count; uint material; float time; float previous_time; uint point_vertices; uint pose; uint dispatch_width; uint deforming; uint4 object_header; float4x4 to_stream; float4x4 from_stream; uint4 addresses; };+[[vk::binding(0,2)]] StructuredBuffer<Evaluation> evaluations : register(t5);+static Evaluation evaluation;[[vk::binding(1,2)]] StructuredBuffer<float> current_source : register(t6);[[vk::binding(2,2)]] StructuredBuffer<float> previous_source : register(t7);// For each evaluation (triangle vertex or point): UV0.xy and attribute slots.@@ -11,24 +12,26 @@ struct Evaluation { uint count; uint material; float time; float previous_time;// Triangles: indices, vertex face offsets and incident triangle ordinals.// Points: authored centre XYZ float bits.[[vk::binding(4,2)]] StructuredBuffer<uint> topology : register(t9);-[[vk::binding(5,2)]] RWStructuredBuffer<float> displaced_positions : register(u10);+// Positions are float bits; the trailing job bounds use ordered uint atomics.+[[vk::binding(5,2)]] RWStructuredBuffer<uint> evaluation_scratch : register(u10);[[vk::binding(6,2)]] RWStructuredBuffer<float> current_output : register(u11);[[vk::binding(7,2)]] RWStructuredBuffer<float> previous_output : register(u12);-// Ordered float keys for min/max XYZ; word 6 flags nonfinite evaluation.-[[vk::binding(8,2)]] RWStructuredBuffer<uint> evaluated_bounds : register(u13);+// Per-job bounds contain ordered min/max XYZ; word 6 flags nonfinite evaluation.uint float_key(float v) {let b=asuint(v);return (b&0x80000000u)!=0u ? ~b : (b^0x80000000u);}-float source_word(uint at,uint pose) {if(pose==0u || evaluation.deforming==0u) return current_source[at];+float source_word(uint at,uint pose) {if(pose==0u || evaluation.deforming==0u) return current_source[evaluation.addresses.x+at];return previous_source[(at/10u)*20u+(pose-1u)*10u+at%10u];}float3 source_vector(uint at,uint pose) {return float3(source_word(at,pose),source_word(at+1u,pose),source_word(at+2u,pose));}-float3 position(uint vertex,uint pose) {let at=(pose*evaluation_count()+vertex)*3u;return float3(displaced_positions[at],displaced_positions[at+1u],displaced_positions[at+2u]);}-void output_word(uint at,uint pose,float value) {if(pose==0u) current_output[at]=value;else previous_output[(at/10u)*20u+(pose-1u)*10u+at%10u]=value;}+float3 position(uint vertex,uint pose) {let at=evaluation.addresses.z+(pose*evaluation_count()+vertex)*3u;return asfloat(uint3(evaluation_scratch[at],evaluation_scratch[at+1u],evaluation_scratch[at+2u]));}+void output_word(uint at,uint pose,float value) {if(pose==0u) current_output[evaluation.addresses.y+at]=value;else previous_output[evaluation.addresses.y*2u+(at/10u)*20u+(pose-1u)*10u+at%10u]=value;}uint evaluation_count() {return evaluation.count/max(evaluation.point_vertices,1u);}uint attribute_stride() {return 1u+VORK_ATTRIBUTES;}-[shader("compute")][numthreads(1,1,1)] void initialize() {- for(uint a=0u;a<3u;a++){evaluated_bounds[a]=float_key(asfloat(0x7f800000u));evaluated_bounds[a+3u]=float_key(asfloat(0xff800000u));}- evaluated_bounds[6]=0u;+[shader("compute")][numthreads(1,1,1)] void initialize(uint3 id:SV_DispatchThreadID) {+ evaluation=evaluations[id.z*3u];if(evaluation.object_header.y==0u)return;+ for(uint a=0u;a<3u;a++){evaluation_scratch[evaluation.addresses.w+a]=float_key(asfloat(0x7f800000u));evaluation_scratch[evaluation.addresses.w+a+3u]=float_key(asfloat(0xff800000u));}+ evaluation_scratch[evaluation.addresses.w+6]=0u;}[shader("compute")][numthreads(REG_DEFORM_GROUP,1,1)] void evaluate(uint3 id:SV_DispatchThreadID) {+ evaluation=evaluations[id.z];if(evaluation.object_header.y==0u)return;let vertex=id.x+id.y*evaluation.dispatch_width;let pose=evaluation.pose;if(vertex>=evaluation_count() || pose>=3u)return;#if VORK_ATTRIBUTES > 0for(uint slot=0u;slot<VORK_ATTRIBUTES;slot++) material_attributes[slot]=vertex_attributes[vertex*attribute_stride()+1u+slot];@@ -42,18 +45,19 @@ uint attribute_stride() {return 1u+VORK_ATTRIBUTES;}let record=material_records[evaluation.material];let offset=displacement_dispatch(record.tag.x,local_position,normal,pose==0u ? evaluation.time : evaluation.previous_time,record.tag.w);let result=(evaluation.point_vertices!=0u ? float3(0.) : p)+mul(float4(offset,0.),evaluation.to_stream).xyz;- if(any((asuint(result)&uint3(0x7f800000u))==uint3(0x7f800000u))) {uint ignored;InterlockedOr(evaluated_bounds[6],1u,ignored);}+ if(any((asuint(result)&uint3(0x7f800000u))==uint3(0x7f800000u))) {uint ignored;InterlockedOr(evaluation_scratch[evaluation.addresses.w+6],1u,ignored);}for(uint a=0u;a<3u;a++) {- displaced_positions[(pose*evaluation_count()+vertex)*3u+a]=result[a];- if(pose==0u && evaluation.point_vertices==0u) {uint ignored;InterlockedMin(evaluated_bounds[a],float_key(result[a]),ignored);InterlockedMax(evaluated_bounds[a+3u],float_key(result[a]),ignored);}+ evaluation_scratch[evaluation.addresses.z+(pose*evaluation_count()+vertex)*3u+a]=asuint(result[a]);+ if(pose==0u && evaluation.point_vertices==0u) {uint ignored;InterlockedMin(evaluation_scratch[evaluation.addresses.w+a],float_key(result[a]),ignored);InterlockedMax(evaluation_scratch[evaluation.addresses.w+a+3u],float_key(result[a]),ignored);}}}[shader("compute")][numthreads(REG_DEFORM_GROUP,1,1)] void finish(uint3 id:SV_DispatchThreadID) {+ evaluation=evaluations[id.z];if(evaluation.object_header.y==0u)return;let vertex=id.x+id.y*evaluation.dispatch_width;let pose=evaluation.pose;if(vertex>=evaluation.count || pose>=3u)return;let p=evaluation.point_vertices!=0u ? source_vector(vertex*10u,pose)+position(vertex/max(evaluation.point_vertices,1u),pose) : position(vertex,pose);- if(any((asuint(p)&uint3(0x7f800000u))==uint3(0x7f800000u))) {uint ignored;InterlockedOr(evaluated_bounds[6],1u,ignored);}+ if(any((asuint(p)&uint3(0x7f800000u))==uint3(0x7f800000u))) {uint ignored;InterlockedOr(evaluation_scratch[evaluation.addresses.w+6],1u,ignored);}if(evaluation.point_vertices!=0u && pose==0u) {- for(uint a=0u;a<3u;a++) {uint ignored;InterlockedMin(evaluated_bounds[a],float_key(p[a]),ignored);InterlockedMax(evaluated_bounds[a+3u],float_key(p[a]),ignored);}+ for(uint a=0u;a<3u;a++) {uint ignored;InterlockedMin(evaluation_scratch[evaluation.addresses.w+a],float_key(p[a]),ignored);InterlockedMax(evaluation_scratch[evaluation.addresses.w+a+3u],float_key(p[a]),ignored);}}var normal=source_vector(vertex*10u+3u,pose);var tangent=source_vector(vertex*10u+6u,pose);@@ -96,7 +100,7 @@ uint attribute_stride() {return 1u+VORK_ATTRIBUTES;}sign=dot(cross(normal,tangent),transformed_b)<0. ? -1. : 1.;}}- if(any((asuint(normal)&uint3(0x7f800000u))==uint3(0x7f800000u)) || any((asuint(tangent)&uint3(0x7f800000u))==uint3(0x7f800000u))) {uint ignored;InterlockedOr(evaluated_bounds[6],1u,ignored);}+ if(any((asuint(normal)&uint3(0x7f800000u))==uint3(0x7f800000u)) || any((asuint(tangent)&uint3(0x7f800000u))==uint3(0x7f800000u))) {uint ignored;InterlockedOr(evaluation_scratch[evaluation.addresses.w+6],1u,ignored);}for(uint a=0u;a<3u;a++) {output_word(vertex*10u+a,pose,p[a]);output_word(vertex*10u+3u+a,pose,normal[a]);output_word(vertex*10u+6u+a,pose,tangent[a]);}output_word(vertex*10u+9u,pose,sign);}diff --git a/crates/vork-render/shaders/fibre_capture.slang b/crates/vork-render/shaders/fibre_capture.slangindex 1f7f98a..3f56546 100644--- a/crates/vork-render/shaders/fibre_capture.slang+++ b/crates/vork-render/shaders/fibre_capture.slang@@ -14,7 +14,7 @@ Surface fibre_surface<P:IProgram>(Varying v,bool front) {let entering=material_front(v,front);if (!entering) {discard;}let view=fibre_light_view(v.world);- let k=raster_coordinates(v,surface_geometric(v,entering),view);+ let k=raster_coordinates(v,entering,view);let s=surface_at<Unspecialized,P>(v,entering,view,k);if (!s.is_hair || s.discarded) {discard;}return s;diff --git a/crates/vork-render/shaders/gi_ray.slang b/crates/vork-render/shaders/gi_ray.slangindex 19e105c..a5ff843 100644--- a/crates/vork-render/shaders/gi_ray.slang+++ b/crates/vork-render/shaders/gi_ray.slang@@ -1,7 +1,8 @@#ifdef VORK_DIFFUSE_MEDIUMimport diffuse_medium;+#endif// Preparation is retained with the incident accumulator for this exposure.-struct GiMediumQuery {+struct GiQuery {float4 accumulation;float4 position_depth;float4 normal_view;@@ -9,10 +10,9 @@ struct GiMediumQuery {float4 error;};#ifdef VORK_METAL-[[vk::binding(1,3)]] RWStructuredBuffer<GiMediumQuery> gi_medium_accumulation : register(VORK_GI_MEDIUM_REGISTER);+[[vk::binding(1,3)]] RWStructuredBuffer<GiQuery> gi_accumulation : register(VORK_GI_QUERY_REGISTER);#else-[[vk::binding(1,3)]] RWStructuredBuffer<GiMediumQuery> gi_medium_accumulation;-#endif+[[vk::binding(1,3)]] RWStructuredBuffer<GiQuery> gi_accumulation;#endif// Ray diffuse indirect shades off-screen hits through the raster surface// evaluation (hit.slang) and the shared BSDF evaluator.@@ -48,13 +48,9 @@ import probes;[[vk::binding(14,0)]] RaytracingAccelerationStructure ray_scene : register(t5);[[vk::binding(15,0)]] StructuredBuffer<uint> ray_alpha : register(t6);[[vk::binding(16,0)]] [[vk::image_format("rgba32f")]] RWTexture2D<float4> cell_receivers : register(u8);-#ifdef VORK_DIFFUSE_MEDIUMstruct GiSources {uint4 topology;uint4 batch;};[[vk::binding(17,0)]] ConstantBuffer<GiSources> gi_source_data : register(b7);#define gi_sources gi_source_data.topology-#else-[[vk::binding(17,0)]] ConstantBuffer<uint4> gi_sources : register(b7);-#endif[[vk::binding(18,0)]] StructuredBuffer<float> gi_emitter_weights : register(t8);// Raster geometry buffers ray hits read in place (rt::hit_record, rt::hits_layout).@@ -216,53 +212,44 @@ bool gi_consumed(uint2 cell) {}// Scenes with programs compile their own entry with their Programs (SlangForward::program_kernel).void gi_pixel<V:IVariant,P:IProgram>(uint3 gid) {- if (any(gid.xy>=image_size(output))) {return;}-#ifdef VORK_DIFFUSE_MEDIUM+ if(gid.y>=gi_source_data.batch.z) return;let at=gid.y*image_size(output).x+gid.x;+ gid.y+=gi_source_data.batch.y;+ if (any(gid.xy>=image_size(output))) {return;}let begin=gi_source_data.batch.x;- GiMediumQuery prepared;+ let rays=uint(frame.ao.z)*max(frame.sampling.w,1u);+ if(begin>=rays) return;+ GiQuery prepared;if(begin==0u) {-#endiflet surface=ao_surface(receivers,normals,gid.xy,int(frame.ao.w),frame.view);if(surface.depth<1.) {cell_receivers[gid.xy]=float4(surface.position,surface.depth);}let active=surface.depth<1. && gi_consumed(gid.xy);let ng=active ? screen_geometric_normal(receivers,surface.pixel,surface.position,surface.normal) : surface.normal;let position_error=active ? surface_position_error(surface.object,surface.position) : float3(0.);-#ifdef VORK_DIFFUSE_MEDIUMprepared.accumulation=float4(0.);prepared.position_depth=float4(surface.position,surface.depth);prepared.normal_view=float4(surface.normal,surface.view_depth);prepared.geometric_active=float4(ng,active ? 1. : 0.);prepared.error=float4(position_error,0.);- gi_medium_accumulation[at]=prepared;-#endif+ gi_accumulation[at]=prepared;if(!active) {output[gid.xy]=surface.depth>=1. ? float4(1.,0.,0.,0.) : float4(1.,surface.view_depth,encode_octahedron(surface.normal));incident_output[gid.xy]=float4(0.);return;}-#ifdef VORK_DIFFUSE_MEDIUM- } else {prepared=gi_medium_accumulation[at];}+ } else {prepared=gi_accumulation[at];}// Inactive cells skip every later batch before receiver reconstruction or// the support-aware demand scan. Their first batch published filter guides.if(prepared.geometric_active.w==0.) {return;}let position=prepared.position_depth.xyz;let n=prepared.normal_view.xyz;let view_depth=prepared.normal_view.w;let ng=prepared.geometric_active.xyz;let position_error=prepared.error.xyz;-#else- let position=surface.position;let n=surface.normal;let view_depth=surface.view_depth;- let begin=0u;-#endif- let rays=uint(frame.ao.z)*max(frame.sampling.w,1u);let count=rays*uint(max(frame.temporal.y,1.));let first=uint(frame.temporal.x)*rays;+ let count=rays*uint(max(frame.temporal.y,1.));let first=uint(frame.temporal.x)*rays;let basis=ray_basis(n);// Replacement and radiance estimate the same clipped cosine measure.// The signed residual may be negative at finite sample counts.var hits=0.;var incident=float3(0.);-#ifdef VORK_DIFFUSE_MEDIUM- let end=min(begin+REG_MEDIUM_GI_RAY_BATCH,rays);+ let end=min(begin+REG_GI_RAY_BATCH,rays);incident=prepared.accumulation.xyz;hits=prepared.accumulation.w;-#else- let end=rays;-#endiffor(var k=begin;k<end;k++) {incident+=gi_source<V,P>(position,n,ng,position_error,gid.xy,first+k,count);incident+=gi_field_source<V,P>(position,n,ng,position_error,gid.xy,first+k,count);@@ -326,9 +313,7 @@ void gi_pixel<V:IVariant,P:IProgram>(uint3 gid) {#endifincident+=radiance*direction_weight;}-#ifdef VORK_DIFFUSE_MEDIUM- if(end<rays) {gi_medium_accumulation[at].accumulation=float4(incident,hits);return;}-#endif+ if(end<rays) {gi_accumulation[at].accumulation=float4(incident,hits);return;}let total=float(max(rays,1u));var estimate=incident/total;output[gid.xy]=float4(1.-hits/total,view_depth,encode_octahedron(n));diff --git a/crates/vork-render/shaders/hit_geometry.slang b/crates/vork-render/shaders/hit_geometry.slangindex 97517d6..3530d18 100644--- a/crates/vork-render/shaders/hit_geometry.slang+++ b/crates/vork-render/shaders/hit_geometry.slang@@ -75,7 +75,7 @@ public HitTriangle hit_triangle<G:IHitGeometry>(uint instance, uint primitive, u}// The BLAS winding: object-space corners in index order.let face=cross(t.c[1].POSITION-t.c[0].POSITION,t.c[2].POSITION-t.c[0].POSITION);- t.face=dot(face,face)>0. ? normalize(face) : t.c[0].NORMAL;+ t.face=finite_unit_normal(face,t.c[0].NORMAL);return t;}// stream.slang varying() at barycentrics `b`: the same object transforms.@@ -89,6 +89,7 @@ public Varying hit_varying(HitTriangle t, float3 b) {let tangent=t.c[0].TANGENT*b.x+t.c[1].TANGENT*b.y+t.c[2].TANGENT*b.z;o.rest=t.c[0].rest*b.x+t.c[1].rest*b.y+t.c[2].rest*b.z;o.world=hit_point(t,b);o.NORMAL=mul(t.c[0].NORMAL*b.x+t.c[1].NORMAL*b.y+t.c[2].NORMAL*b.z,t.normal_matrix);+ o.NORMAL=winding_normal(o.NORMAL,mul(t.face,t.normal_matrix));o.TEXCOORD_0=t.c[0].TEXCOORD_0*b.x+t.c[1].TEXCOORD_0*b.y+t.c[2].TEXCOORD_0*b.z;o.TEXCOORD_1=t.c[0].TEXCOORD_1*b.x+t.c[1].TEXCOORD_1*b.y+t.c[2].TEXCOORD_1*b.z;o.COLOR_0=t.c[0].COLOR_0*b.x+t.c[1].COLOR_0*b.y+t.c[2].COLOR_0*b.z;@@ -153,7 +154,7 @@ public float4 hit_shadow_offset(HitTriangle t,float3 b,bool front) {[unroll] for(uint i=0u;i<3u;i++) {p[i]=mul(float4(t.c[i].POSITION-t.c[0].POSITION,0.),model).xyz;let raw=mul(t.c[i].NORMAL,t.normal_matrix);- n[i]=dot(raw,raw)>0. ? normalize(raw)*side : face;+ n[i]=finite_unit_normal(raw*side,face);}return shadow_terminator_geometry(p,n,face,b);}@@ -199,7 +200,7 @@ public float3 solid_exit_normal(float3 interpolated,float3 world_face,float3x3 mreturn solid_exit_normal(shading,geometric,direction,eta);}// The world face normal on the object's front (winding) side.-public float3 hit_face(HitTriangle t) {return normalize(mul(t.face,t.normal_matrix));}+public float3 hit_face(HitTriangle t) {return finite_unit_normal(mul(t.face,t.normal_matrix),float3(0.,0.,1.));}// Current emitter geometry shares the same transformed/deformed corners as hits.public struct HitEmitterGeometry { public float3 point; public float3 face; public float area; };diff --git a/crates/vork-render/shaders/path.slang b/crates/vork-render/shaders/path.slangindex 1dc5736..40a347d 100644--- a/crates/vork-render/shaders/path.slang+++ b/crates/vork-render/shaders/path.slang@@ -633,7 +633,7 @@ float3 next_event<V:IVariant,P:IProgram>(HitSurface shading, Closure c, float3 vif(!source.delta && any(sample.weight>float3(0.)) && dot(sample.direction,sample.direction)>0.&& (contribution&sample.event)!=0u&& (shading.s.is_hair || path_event_hemisphere(c,sample.event,sample.direction,geometric,shading.s.geometric))- && !(c.geometry_thin_walled && !transport_rough_transmission(c) && sample.event==REG_RAY_TRANSMISSION)) {+ && !(transport_null_event(c,media.incident.ior,sample))) {let optical=dot(shading.s.geometric,sample.direction)<0. ? media.transmitted : media.incident;let weight=sample.pdf>0. ? mis_power(sample.pdf,segment_light_pdf<V>(l,world,sample.direction)) : 1.;bsdf_endpoint=sample.weight*(weight/probability)*segment_analytic<V,P>(path_origin(shading,world,error,sample.direction),sample.direction,i,transparent,optical,optical_length,rng);@@ -701,8 +701,8 @@ float3 next_event<V:IVariant,P:IProgram>(HitSurface shading, Closure c, float3 v// It also runs at the last scattering vertex, where NEE is still evaluated.let continuation=hair ? hair_lit: (contribution&sample.event)!=0u && path_event_hemisphere(c,sample.event,sample.direction,geometric,shading.s.geometric);- // Null sheets belong to the preceding connection, not another emitter strategy.- if (continuation && !(c.geometry_thin_walled && !transport_rough_transmission(c) && sample.event==REG_RAY_TRANSMISSION) && dot(sample.direction,sample.direction)>0.) {+ // Null events belong to the preceding connection, not another emitter strategy.+ if (continuation && !(transport_null_event(c,media.incident.ior,sample)) && dot(sample.direction,sample.direction)>0.) {let source=emitter_eval_li<V>(l,world,sample.direction);if (source.pdf>0.) {let weight=sample.pdf>0. ? mis_power(sample.pdf,source.pdf) : 1.;@@ -1306,8 +1306,7 @@ float3 integrate<let spatial_subsurface:bool,V:IVariant,P:IProgram,let N:uint>(fradiance+=clamp_sample(throughput*implicit_next_event<V,P>(shading,c,-direction,world,error,geometric,media,continuation_mask(bounce,diffuse,glossy,transmission),transparent,prepared,sampler,optical_length,rng),select(bounce==0u,path_settings.clamp.x,path_settings.clamp.y));#endif- if (!shading.s.is_hair && transport_null_boundary(c,media.incident.ior)- && sample.event==REG_RAY_TRANSMISSION && sample.pdf==0.) {+ if (!shading.s.is_hair && transport_null_event(c,media.incident.ior,sample)) {if (transparent++>=path_settings.limits.z) {break;}throughput*=sample.weight;if (!all(isfinite(throughput))) {path_boundary_error(REG_RADIANCE_NONFINITE,hit.object);break;}diff --git a/crates/vork-render/shaders/reconstruct.slang b/crates/vork-render/shaders/reconstruct.slangindex 63de286..fc977c0 100644--- a/crates/vork-render/shaders/reconstruct.slang+++ b/crates/vork-render/shaders/reconstruct.slang@@ -38,23 +38,36 @@ void filter(uint3 id:SV_DispatchThreadID) {// and mixed coverage. Reuse that word rather than load raw guide coverage.if(identity<=0.) {destination[i]=center;return;}let coverage=accumulation[i].a/float(params.samples);- var sum=float3(0.);var weights=0.;var variance=0.;+ if(coverage<=0.) {destination[i]=center;return;}+ var sum=center.rgb;var variance=center.a;for(int y=-1;y<=1;y++) for(int x=-1;x<=1;x++) {- let j=index(int2(id.xy)+int2(x,y)*int(params.step));let tap=source[j];+ let position=int2(id.xy)+int2(x,y)*int(params.step);+ // Clamped border taps are not reciprocal. Missing neighbours exchange+ // no energy, leaving their weight at the receiver itself.+ if(any(position<int2(0)) || any(position>=int2(params.width,params.height))) {continue;}+ let j=index(position);let tap=source[j];if(filtered_guides[2*j+1].w!=identity) {continue;}let da=filtered_guides[2*j].rgb-a;let dn=filtered_guides[2*j+1].rgb-n;if(dot(da,da)>RECONSTRUCT_ALBEDO_EDGE_SQUARED) {continue;}let dc=length(tap.rgb-center.rgb)/sqrt(3.);- let alpha=accumulation[j].a/float(params.samples)-coverage;+ let tap_coverage=accumulation[j].a/float(params.samples);+ if(tap_coverage<=0.) {continue;}+ let alpha=tap_coverage-coverage;let spatial=float((x==0?2:1)*(y==0?2:1));let sigma=RECONSTRUCT_COLOR_SIGMA*sqrt(max(center.a+tap.a,RECONSTRUCT_VARIANCE_FLOOR));let weight=spatial*exp(-dot(da,da)*RECONSTRUCT_ALBEDO_SCALE-dot(dn,dn)*RECONSTRUCT_NORMAL_SCALE-abs(dc)/sigma-abs(alpha)*RECONSTRUCT_ALPHA_SCALE);- sum+=tap.rgb*weight;weights+=weight;variance+=tap.a*weight;+ // Off-centre spatial weights sum to 12; the centre exchanges zero.+ // Every pair uses the same conductance+ // and exchanges opposite premultiplied RGB flux; do not normalize each+ // receiver by a different surviving weight sum. min coverage keeps the+ // update convex even at fractional camera coverage.+ let exchange=weight*(min(coverage,tap_coverage)/coverage)/12.;+ sum+=(tap.rgb-center.rgb)*exchange;variance+=(tap.a-center.a)*exchange;}// Keep the local noise scale through coarse levels. Shrinking it after// every pass mistakes residual low-frequency noise for a lighting edge// and freezes moving blotches on otherwise smooth walls.- destination[i]=float4(sum/weights,variance/weights);+ destination[i]=float4(sum,variance);}[shader("compute")] [numthreads(REG_COMPUTE_TILE,REG_COMPUTE_TILE,1)]void finish(uint3 id:SV_DispatchThreadID) {diff --git a/crates/vork-render/shaders/stream.slang b/crates/vork-render/shaders/stream.slangindex 54390ee..0afb400 100644--- a/crates/vork-render/shaders/stream.slang+++ b/crates/vork-render/shaders/stream.slang@@ -189,3 +189,19 @@ OpaqueDepth opaque_single_depth(float3 p, uint object) {o.mirrored=select(dot(cross(model[0].xyz,model[1].xyz),model[2].xyz)<0.,1u,0u);return o;}++// Supplied smooth normals belong to the triangle's winding hemisphere.+// Coverage and dielectric entry/exit continue to use winding, not authored normals.+// Scale first: finite but tiny/large authored vectors must not under/overflow.+float3 finite_unit_normal(float3 normal,float3 fallback) {+ let scale=max(abs(normal.x),max(abs(normal.y),abs(normal.z)));+ if(all(isfinite(normal)) && scale>0.) {return normalize(normal/scale);}+ let fallback_scale=max(abs(fallback.x),max(abs(fallback.y),abs(fallback.z)));+ if(all(isfinite(fallback)) && fallback_scale>0.) {return normalize(fallback/fallback_scale);}+ // A fully collapsed primitive has no face; retain a finite placeholder.+ return float3(0.,0.,1.);+}+float3 winding_normal(float3 normal,float3 face) {+ let unit=finite_unit_normal(normal,face);+ return dot(unit,face)<0. ? -unit : unit;+}diff --git a/crates/vork-render/shaders/surface.slang b/crates/vork-render/shaders/surface.slangindex 9d5b230..808d714 100644--- a/crates/vork-render/shaders/surface.slang+++ b/crates/vork-render/shaders/surface.slang@@ -31,7 +31,12 @@ struct Coordinates {};// TEXCOORD_1, or zero for draws without one (tangent w carries the flag).float2 varying_uv1(Varying v) {return select(abs(v.TANGENT.w)>=2.,float2(0.),v.TEXCOORD_1);}-Coordinates raster_coordinates(Varying v, float3 geometric, float3 incident) {+Coordinates raster_coordinates(inout Varying v, bool object_front, float3 incident) {+ // The derivative cross has screen orientation; recover the object's winding side.+ let face=cross(ddx(v.world),ddy(v.world));+ let winding=face*select(dot(face,incident)>=0.,1.,-1.)*select(object_front,1.,-1.);+ v.NORMAL=winding_normal(v.NORMAL,winding);+ let geometric=surface_geometric(v,object_front);Coordinates k;k.material_filter=float3(0.);k.shadow_offset=float4(0.);let uv1=varying_uv1(v);k.position_dx=ddx(v.world);k.position_dy=ddy(v.world);@@ -286,7 +291,7 @@ Surface surface_at<V:IVariant, P:IProgram,let decode_table:bool=true>(Varying v,if ((material_records[record].tag.z®_FLAG_GLTF_UNLIT)!=0u) { evaluated.closure.emission_color=evaluated.closure.base_color;evaluated.closure.emission_luminance=1.; }return evaluated;}-float3 surface_geometric(Varying v, bool object_front) {return normalize(v.NORMAL)*select(object_front,1.,-1.);}+float3 surface_geometric(Varying v, bool object_front) {return finite_unit_normal(v.NORMAL,float3(0.,0.,1.))*select(object_front,1.,-1.);}Surface surface<V:IVariant, P:IProgram>(Varying v, bool front) {return surface<V,P>(v,front,0u);}Surface surface<V:IVariant, P:IProgram>(Varying v, bool front, uint lobe) {Coordinates k;return surface<V,P>(v,front,lobe,k);}// `k`: the fragment's coordinates, for a later lit stage.@@ -302,7 +307,7 @@ Surface surface<V:IVariant, P:IProgram>(Varying v, bool front, uint lobe, out Coif (!material_covers_side<V>(v,object_front)) {discard;}let view=camera_view(v.world,frame);// Derivatives first: everything after the record read is non-uniform.- k=raster_coordinates(v,surface_geometric(v,object_front),view);+ k=raster_coordinates(v,object_front,view);let s=surface_at<V,P>(v,object_front,view,k,Lobe(lobe,0.));if (V.has_mask) {return raster_coverage(v,s,index,count);}return s;@@ -337,7 +342,7 @@ Surface raster_coverage(Varying v, Surface s, uint index, uint count) {float program_shadow_opacity<P:IProgram>(Varying v, bool front) {let object_front=material_front(v,front);let view=camera_view(v.world,frame);- let k=raster_coordinates(v,surface_geometric(v,object_front),view);+ let k=raster_coordinates(v,object_front,view);let s=surface_at<Unspecialized,P>(v,object_front,view,k);return candidate_scalar_opacity(material_record(v.object),s.closure.geometry_opacity);}diff --git a/crates/vork-render/src/attributes.rs b/crates/vork-render/src/attributes.rsindex 0cafac4..820f108 100644--- a/crates/vork-render/src/attributes.rs+++ b/crates/vork-render/src/attributes.rs@@ -91,7 +91,7 @@ pub(crate) fn resolve<'a>(scene: &'a v2::Scene, node: &v2::Node, name: &str) ->ensure!(vertex.is_none() || instance.is_none(), "attribute {name:?} exists on both geometry and instances");let buffer = vertex.or(instance).with_context(|| format!("missing attribute {name:?}"))?;if vertex.is_none() && scene.programs.values().any(|p| p.is_compute() && p.bindings.values().any(|b| b == buffer)) {- eprintln!("warning: node {:?}: ignored compute updates to material attribute {name:?}; using authored values",node.name);+ crate::warnings::dropped("computed_attribute", serde_json::json!({"node":node,"attribute":name,"buffer":buffer}), format!("warning: node {:?}: ignored compute updates to material attribute {name:?}; using authored values",node.name));}Ok(scene.buffers.get_key_value(buffer).context("unknown attribute buffer")?.0)}diff --git a/crates/vork-render/src/camera_program.rs b/crates/vork-render/src/camera_program.rsindex 906b8a0..d06a205 100644--- a/crates/vork-render/src/camera_program.rs+++ b/crates/vork-render/src/camera_program.rs@@ -96,8 +96,9 @@ pub(crate) fn install(r: &Renderer, scene: &v2::Scene, nodes: &mut [EvalNode], blet mut hash=blake3::Hasher::new();hash.update(b"camera-optics-v3");hash.update(abi.cache_identity()?.as_bytes());hash.update(source.as_bytes());hash.update(origin.to_string_lossy().as_bytes());let key=hash.finalize();let tag=key.to_hex();- let program=programs::cached(r,key,|p:&vork_slang::CameraProgram|&p.dependencies,- ||vork_slang::Compiler::discover().compile_camera(&abi,&source,&origin,&tag[..12]))?;+ let program=programs::cached(r,key,&vork_slang::Compiler::discover(),+ &abi, &source, &origin,+ |compiler|compiler.compile_camera(&abi,&source,&origin,&tag[..12]))?;let values=material.inputs.iter().map(|(k,v)|Ok((k.clone(),serde_json::to_value(v)?))).collect::<Result<BTreeMap<_,_>>>()?;let words=program.inputs.pack(&values,|name,_|bail!("camera input {name} must be numeric"))?;let varying=program.inputs.varying_words(&words,dynamic.get(&name).unwrap_or(&BTreeSet::new()));@@ -231,18 +232,18 @@ pub(crate) fn scene_spectral(r: &Renderer, scene: &v2::Scene, base: &Path) -> Relet (source,origin)=if let Some(source)=vork_slang::module_source(&material.program) {(source.to_owned(),PathBuf::from(format!("{}.slang",material.program)))} else {programs::program_source(base,&material.program,&scene.programs[&material.program])?};- let mut hash=blake3::Hasher::new();hash.update(b"spectral-surface-v1");hash.update(abi.cache_identity()?.as_bytes());hash.update(source.as_bytes());hash.update(origin.to_string_lossy().as_bytes());- let key=hash.finalize();let tag=key.to_hex();if medium {+ let mut hash=blake3::Hasher::new();hash.update(b"spectral-surface-v1");hash.update(abi.cache_identity()?.as_bytes());hash.update(source.as_bytes());hash.update(origin.to_string_lossy().as_bytes());+ let tag=hash.finalize().to_hex();let mut medium_key=hash.clone();medium_key.update(b"medium");- let program=programs::cached(r,medium_key.finalize(),|p:&vork_slang::MediumProgram|&p.dependencies,- ||vork_slang::Compiler::discover().compile_medium(&abi,&source,&origin,&tag[..12]))?;+ let program=programs::cached(r,medium_key.finalize(),&vork_slang::Compiler::discover(),+ &abi, &source, &origin,+ |compiler|compiler.compile_medium(&abi,&source,&origin,&tag[..12]))?;let values=material.inputs.iter().map(|(k,v)|Ok((k.clone(),serde_json::to_value(v)?))).collect::<Result<BTreeMap<_,_>>>()?;if program.needs_spectral(&abi,&program.inputs.effect_words(&values,&varying)?)? {return Ok(true);}if !surface {continue;}}- let program=programs::cached(r,key,|p:&vork_slang::Program|&p.dependencies,- ||vork_slang::Compiler::discover().compile_surface(&abi,&source,&origin,&tag[..12]))?;+ let program=programs::compile(r,&vork_slang::Compiler::discover(),&abi,&source,&origin)?;let values=material.inputs.iter().map(|(k,v)|Ok((k.clone(),serde_json::to_value(v)?))).collect::<Result<BTreeMap<_,_>>>()?;if program.needs_spectral(&abi,&program.inputs.effect_words(&values,&varying)?)? {return Ok(true);}}diff --git a/crates/vork-render/src/compositor.rs b/crates/vork-render/src/compositor.rsindex 687bdb3..96ce295 100644--- a/crates/vork-render/src/compositor.rs+++ b/crates/vork-render/src/compositor.rs@@ -141,9 +141,10 @@ pub(crate) fn install(let compiled = programs::cached(r,key,- |p: &CompositeProgram| &p.dependencies,- || {- Compiler::discover().compile_composite_bound(+ &Compiler::discover(),+ &abi, &source, &origin,+ |compiler| {+ compiler.compile_composite_bound(&abi,&source,&origin,diff --git a/crates/vork-render/src/compositor/images.rs b/crates/vork-render/src/compositor/images.rsindex 08e98d6..1206913 100644--- a/crates/vork-render/src/compositor/images.rs+++ b/crates/vork-render/src/compositor/images.rs@@ -314,7 +314,7 @@ pub(super) fn pass(let mut authored:Vec<_>=layout.iter().map(|entry|entry.binding).collect();authored.sort_unstable();let slots:Vec<_>=authored.into_iter().enumerate().map(|(physical,authored)|(0,authored,physical as u32)).collect();let mut hash=blake3::Hasher::new();hash.update(b"native-image-hlsl-9");hash.update(vork_slang::VERSION.as_bytes());hash.update(&serde_json::to_vec(&slots)?);hash.update(shader.as_bytes());- let code:Vec<u8>=programs::cached(r,hash.finalize(),|_|&[],||Compiler::discover().compile_image_spirv(&shader,&slots))?;+ let code:Vec<u8>=programs::cached_generated(r,hash.finalize(),||Compiler::discover().compile_image_spirv(&shader,&slots))?;crate::native::module(d,"compositor image pass",Some(&code),None,(group[0],group[1],1))} else {crate::timing::shader_module(d,wgpu::ShaderModuleDescriptor {label:Some("compositor image pass"),source:wgpu::ShaderSource::Wgsl(shader.into())})diff --git a/crates/vork-render/src/compute.rs b/crates/vork-render/src/compute.rsindex 7e2afa4..42800f5 100644--- a/crates/vork-render/src/compute.rs+++ b/crates/vork-render/src/compute.rs@@ -403,12 +403,17 @@ impl Compute {).as_bytes(),);+ let abi=programs::abi();+ let compiler=vork_slang::Compiler::discover();+ let inputs=programs::bound_program_identity(&r.disk_cache,&compiler,&abi,&text,&origin,&header)?;+ let compiler=compiler.with_identity(&inputs);let artifact = programs::cached(r,key,- |p: &vork_slang::ComputeProgram| &p.dependencies,- || {- vork_slang::Compiler::discover().compile_compute(+ &compiler,+ &abi, &text, &origin,+ |compiler| {+ compiler.compile_compute(&text,&origin,&header,@@ -419,7 +424,9 @@ impl Compute {)?;if program.schedule == Some(ComputeSchedule::Simulation) {identity.update(key.as_bytes());- for file in &artifact.dependencies { identity.update(&std::fs::read(file)?); }+ // Bind retained simulation to the compiled code and reflected+ // defaults, never to dependency bytes reopened after compilation.+ identity.update(&serde_json::to_vec(&artifact)?);}if !artifact.warnings.trim().is_empty() {eprintln!("{}", artifact.warnings.trim());diff --git a/crates/vork-render/src/computed_geometry.rs b/crates/vork-render/src/computed_geometry.rsindex dd6715e..d167b48 100644--- a/crates/vork-render/src/computed_geometry.rs+++ b/crates/vork-render/src/computed_geometry.rs@@ -787,7 +787,7 @@ pub(crate) fn evaluate(frame.readback.unmap();}if let Some((i, flags)) = error {- anyhow::bail!(+ return Err(anyhow::anyhow!("computed geometry draw {i}: {}",if flags & 1 != 0 {"live count exceeds installed capacity"@@ -796,7 +796,7 @@ pub(crate) fn evaluate(} else {"nonfinite attribute or negative/nonfinite width"}- );+ ).context(crate::failure::FailureKind::Scene));}Ok(result)}diff --git a/crates/vork-render/src/constants.rs b/crates/vork-render/src/constants.rsindex e965809..245d4d0 100644--- a/crates/vork-render/src/constants.rs+++ b/crates/vork-render/src/constants.rs@@ -289,5 +289,5 @@ pub(crate) const SIMULATION_GROUP_OBSERVATIONS: usize = 3;/// Baseline windows between larger-group trials after a failed trial.pub(crate) const SIMULATION_GROUP_RETRY: u32 = 8;-/// GiMediumQuery in gi_ray.slang: five aligned float4 records per query.-pub(crate) const GI_MEDIUM_QUERY_BYTES: u64 = 80;+/// GiQuery in gi_ray.slang: five aligned float4 records per query.+pub(crate) const GI_QUERY_BYTES: u64 = 80;diff --git a/crates/vork-render/src/denoise.rs b/crates/vork-render/src/denoise.rsindex 9780aa8..958cdb8 100644--- a/crates/vork-render/src/denoise.rs+++ b/crates/vork-render/src/denoise.rs@@ -218,7 +218,7 @@ impl Engine {/// Positive tristimulus channels are scalar signals, not RGB chroma./// Replicate each into neutral RGB so the learned RGB colour prior cannot/// mix physically unrelated matching functions. Retain the network's local- /// reconstruction and its fixed scene-linear scale; no energy gain follows.+ /// reconstruction in the caller's pre-exposed units; no energy gain follows.fn denoise_spectral(&mut self, settings: &Denoiser, size: [u32;2], color: &mut [[f32;3]],albedo: &[[f32;3]], normals: &[[f32;3]], use_guides: bool) -> Result<()> {let mut scalar=vec![[0.;3];color.len()];@@ -278,8 +278,8 @@ impl Engine {for (name, buffer) in &guides {filter.image(name, buffer, size);}unsafe {(self.device.api.boolean)(filter.handle, c"hdr".as_ptr(), true);- // Scene-linear radiance has a fixed physical scale. Per-image HDR- // autoexposure couples every pixel to unrelated sampling roundoff.+ // Beauty is already in authored pre-exposure units. Per-image HDR+ // autoexposure would couple pixels to unrelated sampling roundoff.(self.device.api.float)(filter.handle, c"inputScale".as_ptr(), 1.);(self.device.api.boolean)(filter.handle, c"cleanAux".as_ptr(), true);(self.device.api.integer)(filter.handle, c"quality".as_ptr(), quality);@@ -546,6 +546,7 @@ impl Stage {r: &Renderer,encoder: &mut wgpu::CommandEncoder,samples: usize,+ input_scale: f32,timing: &mut Timing,segments: &mut crate::command_finish::Segments,) -> Result<()> {@@ -564,7 +565,7 @@ impl Stage {timing.wait_ms += start.elapsed().as_secs_f64()*1000.;if feedback.rejected() { return Ok(()); }}- return gpu.run(self, r, encoder, samples, timing, segments);+ return gpu.run(self, r, encoder, samples, input_scale, timing, segments);}let staging = self.staging.as_ref().context("OIDN CPU staging missing")?;let start = std::time::Instant::now();@@ -607,6 +608,7 @@ impl Stage {if self.spectral {for rgb in color.iter_mut().chain(albedo.iter_mut()) { *rgb=spectral_color(*rgb,false); }}+ for rgb in &mut color { for c in rgb { *c *= input_scale; } }let pack_ms = pack_start.elapsed().as_secs_f64() * 1000.;let filter_start = std::time::Instant::now();let mut engine=r.denoiser.lock().map_err(|_| anyhow::anyhow!("OIDN engine lock poisoned"))?;@@ -614,6 +616,7 @@ impl Stage {if self.spectral {engine.denoise_spectral(&self.settings,self.size,&mut color,&albedo,&normals,self.use_guides)?;}else {engine.denoise(&self.settings,self.size,&mut color,&albedo,&normals,self.use_guides)?;}let filter_ms = filter_start.elapsed().as_secs_f64() * 1000.;+ for rgb in &mut color { for c in rgb.iter_mut() { *c /= input_scale; } }if self.spectral { for rgb in &mut color { *rgb=spectral_color(*rgb,true); } }let upload_start = std::time::Instant::now();for ((p, rgb), surface) in associated.iter_mut().zip(color).zip(surface) {diff --git a/crates/vork-render/src/denoise/gpu.rs b/crates/vork-render/src/denoise/gpu.rsindex 045ed26..4404622 100644--- a/crates/vork-render/src/denoise/gpu.rs+++ b/crates/vork-render/src/denoise/gpu.rs@@ -276,7 +276,7 @@ impl Stage {Self {layout,pack,unpack}}pub(super) fn run(&self, stage: &super::Stage, r: &Renderer, encoder: &mut wgpu::CommandEncoder,- samples: usize, timing: &mut Timing, segments: &mut crate::command_finish::Segments) -> Result<()> {+ samples: usize, input_scale: f32, timing: &mut Timing, segments: &mut crate::command_finish::Segments) -> Result<()> {use wgpu::util::DeviceExt;let mut engine=r.denoiser.lock().map_err(|_| anyhow::anyhow!("OIDN engine lock poisoned"))?;let engine=engine.as_mut().context("OIDN runtime not initialized")?;@@ -324,7 +324,7 @@ impl Stage {let count=stage.size[0]*stage.size[1];for channel in 0..if stage.spectral {3} else {1} {let params=r.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {label:Some("OIDN preparation parameters"),- contents:bytemuck::cast_slice(&[count,samples as u32,stage.guide_alpha as u32,stage.size[0],stage.spectral as u32,channel,0,0]),usage:wgpu::BufferUsages::UNIFORM});+ contents:bytemuck::cast_slice(&[count,samples as u32,stage.guide_alpha as u32,stage.size[0],stage.spectral as u32,channel,input_scale.to_bits(),0]),usage:wgpu::BufferUsages::UNIFORM});let buffers=[¶ms,&stage.accumulation,&stage.guides,&workspace.shared.buffer,&stage.output];let entries:Vec<_>=buffers.iter().enumerate().map(|(i,b)|wgpu::BindGroupEntry {binding:i as u32,resource:b.as_entire_binding()}).collect();let bindings=r.device.create_bind_group(&wgpu::BindGroupDescriptor {label:Some("OIDN preparation"),layout:&self.layout,entries:&entries});@@ -394,13 +394,17 @@ mod tests {let r=Renderer::new()?;// Exercise non-workgroup widths, alpha, background, no guides, retained// filters, resolution changes, and repeated handoffs of shared memory.- for (size,guided,spectral) in [([73,31],true,false),([73,31],true,true),([19,41],false,true),([73,31],true,false)] {+ // Force the host-staging fallback too; its pre-exposure must match the+ // same independently filtered working-unit reference.+ for cpu in [false, true] {+ if cpu { *r.denoiser.lock().unwrap() = Some(Engine::new()?); }+ for (size,guided,spectral,scale) in [([73,31],true,false,1_f32),([73,31],true,true,131072.),([19,41],false,true,0.03125),([73,31],true,false,131072.)] {let count=(size[0]*size[1]) as usize;let samples=4;let associated:Vec<[f32;4]>=(0..count).map(|i| {let alpha=if i%13==0 {0.} else {0.5};let rgb=if spectral {[-0.25,0.5,0.125]} else {[(i%17) as f32/17.,0.4,0.8]};- [alpha*rgb[0],alpha*rgb[1],alpha*rgb[2],alpha].map(|x| x*samples as f32)+ [alpha*rgb[0]/scale,alpha*rgb[1]/scale,alpha*rgb[2]/scale,alpha].map(|x| x*samples as f32)}).collect();let guides:Vec<[f32;4]>=(0..count).flat_map(|i| {let a=if i%7==0 {0.} else {2.};@@ -414,7 +418,7 @@ mod tests {let mut stage=super::super::Stage::new(&r,&Denoiser::default(),&accumulation,&output,&guide_buffer,true,guided,size)?;stage.spectral=spectral;let device=r.denoiser.lock().unwrap().as_ref().unwrap().device.clone();- ensure!(device.gpu,"test requires GPU OIDN; CPU fallback cannot validate interop");+ ensure!(device.gpu!=cpu,"test must exercise the requested OIDN backend");let mut bytes=bytemuck::cast_slice(&associated).to_vec();bytes.extend_from_slice(bytemuck::cast_slice(&guides));let Inputs {mut color,mut albedo,normals,..}=unpack_inputs(&bytes,samples,count,true);@@ -422,11 +426,13 @@ mod tests {if spectral {for rgb in color.iter_mut().chain(albedo.iter_mut()) { *rgb=spectral_color(*rgb,false); }}+ for rgb in &mut color {for c in rgb {*c*=scale;}}if spectral {reference.denoise_spectral(&Denoiser::default(),size,&mut color,&albedo,&normals,guided)?;}else {reference.denoise(&Denoiser::default(),size,&mut color,&albedo,&normals,guided)?;}+ for rgb in &mut color {for c in rgb.iter_mut() {*c/=scale;}}if spectral {for rgb in &mut color { *rgb=spectral_color(*rgb,true); }}let mut encoder=r.device.create_command_encoder(&Default::default());- stage.run(&r,&mut encoder,samples,&mut Timing::default(),&mut crate::command_finish::Segments::default())?;+ stage.run(&r,&mut encoder,samples,scale,&mut Timing::default(),&mut crate::command_finish::Segments::default())?;let readback=r.device.create_buffer(&wgpu::BufferDescriptor {label:None,size:(count*16) as u64,usage:wgpu::BufferUsages::COPY_DST|wgpu::BufferUsages::MAP_READ,mapped_at_creation:false});encoder.copy_buffer_to_buffer(&output,0,&readback,0,(count*16) as u64);@@ -439,10 +445,11 @@ mod tests {let actual:[f32;4]=std::array::from_fn(|c| f32::from_ne_bytes(pixel[c*4..c*4+4].try_into().unwrap()));let mut expected=associated[i].map(|x|x/samples as f32);if guides[2*i][3]>0. {for c in 0..3 {expected[c]=color[i][c]*expected[3];}}- for c in 0..4 {assert!((actual[c]-expected[c]).abs()<2e-4,"{size:?} guided={guided} pixel {i}: {actual:?} != {expected:?}");}+ for c in 0..4 {assert!((actual[c]-expected[c]).abs()*(if c<3 {scale} else {1.})<2e-4,"{size:?} guided={guided} pixel {i}: {actual:?} != {expected:?}");}}drop(data);readback.unmap();}+ }Ok(())}}diff --git a/crates/vork-render/src/denoise/spatial.rs b/crates/vork-render/src/denoise/spatial.rsindex 07a2ca5..27d9005 100644--- a/crates/vork-render/src/denoise/spatial.rs+++ b/crates/vork-render/src/denoise/spatial.rs@@ -176,6 +176,7 @@ mod tests {use wgpu::util::DeviceExt;#[test]#[ignore = "requires GPU and pinned Slang; runs in the main GPU contracts"]+ #[cfg(vork_private_tests)]fn raster_hdr_silhouette_without_surface_guides_stays_unfiltered() -> Result<()> {let r = crate::test_renderer()?.expect("GPU required");let mut value: serde_json::Value = serde_json::from_str(include_str!("../../../../examples/compositor-bloom.json"))?;@@ -369,6 +370,33 @@ mod tests {assert!(rms < 0.04, "noise residual {rms}");let mean = smooth.iter().map(|p| p[0]).sum::<f32>() / count as f32;assert!((mean - 0.5).abs() < 0.005, "mean energy {mean}");+ // Nonuniform HDR signal, including image borders, fractional coverage,+ // material edges and protected/no-guide pixels. The global RGB sum is+ // an independent conservation invariant, not another filter reference.+ let mut input=Vec::<[f32;4]>::new();let mut varied_guides=Vec::<[f32;4]>::new();+ for i in 0..count {+ let coverage=[0.25,0.5,0.75,1.][i%4];+ let rgb=if i%23==0 {[8.,2.,0.4]} else {[0.02*(i%7) as f32,0.03,0.01]};+ input.push([rgb[0]*coverage,rgb[1]*coverage,rgb[2]*coverage,coverage]);+ let identity=if i%19==0 {-1.} else if i%17==0 {0.} else if i%5==0 {2.} else {1.};+ let a=coverage*samples as f32;let albedo=if i%11==0 {0.8} else {0.2};+ varied_guides.extend([[albedo*a,albedo*a,albedo*a,a],[0.,a,0.,identity]]);+ }+ let result=filter(&input,&varied_guides)?;+ for (i,p) in result.iter().enumerate() {+ assert!(p.iter().all(|x|x.is_finite()));+ assert!((p[3]-input[i][3]).abs()<1e-7);+ for c in 0..3 {+ assert!(p[c]>=-1e-7 && p[c]/p[3]<=[8.,2.,0.4][c]+1e-5,"new radiance extremum: {p:?}");+ if varied_guides[2*i+1][3]<=0. {assert!((p[c]-input[i][c]).abs()<1e-6,"protected pixel changed");}+ }+ }+ for c in 0..3 {+ let before:f64=input.iter().map(|p|f64::from(p[c])).sum();+ let after:f64=result.iter().map(|p|f64::from(p[c])).sum();+ eprintln!("reconstruction RGB[{c}] {before} -> {after}");+ assert!((after-before).abs()<before*2e-6,"reconstruction changed image energy");+ }Ok(())}}diff --git a/crates/vork-render/src/disk_cache.rs b/crates/vork-render/src/disk_cache.rsindex fec5873..27b5b76 100644--- a/crates/vork-render/src/disk_cache.rs+++ b/crates/vork-render/src/disk_cache.rs@@ -256,7 +256,7 @@ fn read_with_shaders(path: &Path, shaders: Option<&Path>) -> Option<Vec<u8>> {let name = path.file_name()?.to_str()?;let (key, kind) = name.split_once('.')?;if key.len() != 64 || !key.bytes().all(|b| b.is_ascii_hexdigit())- || !matches!(kind, "slang-variant-v1.entry" | "slang-program-v1.entry"+ || !matches!(kind, "slang-variant-v1.entry" | "slang-program-v2.entry"| "slang-resolve-v2.entry" | "aov-resolve-v1.entry") {return None;}@@ -460,7 +460,7 @@ mod tests {let store = Store::for_test(root.join("cache"));let shaders = root.join("shaders");for kind in ["slang-variant", "slang-program", "slang-resolve", "aov-resolve", "pipeline", "pipeline-keys", "shader-warm"] {- let version = if kind == "slang-resolve" {2} else {1};+ let version = if matches!(kind, "slang-resolve" | "slang-program") {2} else {1};let path = store.path(kind, version, blake3::hash(b"fixture"));let shipped = shaders.join(path.file_name().unwrap());write(&shipped, b"shipped").unwrap();diff --git a/crates/vork-render/src/displacement.rs b/crates/vork-render/src/displacement.rsindex 75918a2..d7f1b33 100644--- a/crates/vork-render/src/displacement.rs+++ b/crates/vork-render/src/displacement.rs@@ -84,11 +84,18 @@ impl Mesh {}}+fn batch_capacity(limits: &wgpu::Limits) -> usize {+ ((u64::from(limits.max_storage_buffer_binding_size).min(limits.max_buffer_size)+ / (3 * std::mem::size_of::<Parameters>()) as u64) as usize)+ .min(limits.max_compute_workgroups_per_dimension as usize / 3)+}+pub(crate) struct Pipeline {initialize: wgpu::ComputePipeline,evaluate: wgpu::ComputePipeline,finish: wgpu::ComputePipeline,layout: wgpu::BindGroupLayout,+ capacity: usize,}impl Pipeline {pub(crate) fn new(@@ -101,18 +108,12 @@ impl Pipeline {r.device.limits().max_storage_buffers_per_shader_stage >= 11,"material displacement requires eleven storage buffer bindings");- let entries: Vec<_> = (0..9)+ let entries: Vec<_> = (0..8).map(|binding| {pipelines::buffer_entry(binding,wgpu::ShaderStages::COMPUTE,- if binding == 0 {- wgpu::BufferBindingType::Uniform- } else {- wgpu::BufferBindingType::Storage {- read_only: binding < 5,- }- },+ wgpu::BufferBindingType::Storage { read_only: binding < 5 },)}).collect();@@ -136,6 +137,7 @@ impl Pipeline {} else {forward_variant::SPIRV_TARGET};+ let capacity = batch_capacity(&r.device.limits());let define = format!("-DVORK_ATTRIBUTES={attributes}");let includes: Vec<_> = native_programs.include@@ -166,6 +168,10 @@ impl Pipeline {);modules.push(("displacement", source));let compile = |entry: &str| -> Result<wgpu::ComputePipeline> {+ let compiler=vork_slang::Compiler::discover();+ let (identity,prepared)=crate::programs::native_input_identity(+ &|key|r.disk_cache.path("material-displacement",1,key),&compiler,&modules,"displacement",&[(entry,"compute")],&args,&native_programs.identities)?;+ for input in &native_programs.inputs {identity.verify(input)?;}let mut key = blake3::Hasher::new();for part in [target, entry, define.as_str()] {key.update(part.as_bytes());@@ -173,10 +179,7 @@ impl Pipeline {for argument in &args {key.update(argument.as_bytes());}- for (name, text) in &modules {- key.update(name.as_bytes());- key.update(text.as_bytes());- }+ key.update(&identity.identity);let path = r.disk_cache.path("material-displacement", 1, key.finalize());@@ -184,12 +187,9 @@ impl Pipeline {code} else {let start=std::time::Instant::now();- let code = vork_slang::Compiler::discover().compile_modules(- &modules,- "displacement",- &[(entry, "compute")],- &args,- )?;+ let prepared=match prepared {Some(input)=>input,None=>compiler.prepare_identified_modules(&modules,"displacement",&[(entry,"compute")],&args,&native_programs.identities)?};+ anyhow::ensure!(prepared.identity()==identity.identity,"Slang inputs changed during cache lookup; retry the command");+ let code = prepared.compile()?;crate::timing::creation(&r.device,entry,"Slang",start.elapsed().as_secs_f64()*1000.,0.);let _ = disk_cache::write(&path, &code);code@@ -230,6 +230,7 @@ impl Pipeline {evaluate: compile("evaluate")?,finish: compile("finish")?,layout,+ capacity,})}}@@ -248,6 +249,8 @@ struct Parameters {object_header: [u32; 4],to_stream: Mat4,from_stream: Mat4,+ /// Source words, output words, scratch words and bounds words within pages.+ addresses: [u32; 4],}/// Deterministic frame-private page addresses, also used by installed hit records.@@ -324,146 +327,110 @@ pub(crate) fn resources(),);}- Ok(s.draws- .iter()- .enumerate()- .map(|(i, draw)| {- let mesh = draw.displacement.as_ref()?;- if draw.displacement_leader.is_some_and(|leader| leader != i) {- return None;- }- let (leader, offset) = ranges[i]?;- let (current, previous) = &streams[&leader];- let size = u64::from(mesh.count) * 40;- Some(Frame::new(- r,- pipeline,- mesh,- skin[i].as_ref(),- EvaluatedGeometry {- attributes: None,- output: geometry::VertexStream {- buffer: current.clone(),- offset,- size,- },- previous_output: geometry::VertexStream {- buffer: previous.clone(),- offset: offset * 2,- size: size * 2,+ // A batch owns its control resources. Jobs retain only their logical identity+ // and output range. Equal source/topology and destination pages share bindings.+ let mut groups: std::collections::HashMap<_, Vec<usize>> = std::collections::HashMap::new();+ for (i, draw) in s.draws.iter().enumerate() {+ let Some(mesh) = &draw.displacement else { continue };+ if draw.displacement_leader.is_some_and(|leader| leader != i) { continue; }+ let (leader, _) = ranges[i].unwrap();+ let source = skin[i].as_ref().map_or(&mesh.source, |s| &s.output.buffer);+ let previous = skin[i].as_ref().map_or(&mesh.source, |s| &s.previous_output);+ let (source_offset, source_size) = skin[i].as_ref().map_or((0, source.size()),+ |s| (s.output.offset, s.output.size));+ groups.entry((source.clone(), source_offset, source_size, previous.clone(), mesh.attributes.clone(),+ mesh.topology.clone(), leader)).or_default().push(i);+ }+ let mut frames: Vec<Option<Frame>> = (0..s.draws.len()).map(|_| None).collect();+ for ((source, source_offset, source_size, previous, attributes, topology, leader), jobs) in groups {+ let (current, endpoints) = &streams[&leader];+ for jobs in jobs.chunks(pipeline.capacity) {+ let mesh = s.draws[jobs[0]].displacement.as_ref().unwrap();+ let batch = Arc::new(Batch::new(r, pipeline, mesh, jobs, &source, source_offset, source_size, &previous,+ &attributes, &topology, current, endpoints));+ for (slot, &i) in jobs.iter().enumerate() {+ let (_, offset) = ranges[i].unwrap();+ let size = u64::from(mesh.count) * 40;+ frames[i] = Some(Frame {+ geometry: EvaluatedGeometry {+ attributes: None,+ output: geometry::VertexStream { buffer: current.clone(), offset, size },+ previous_output: geometry::VertexStream {+ buffer: endpoints.clone(), offset: offset * 2, size: size * 2,+ },},- },- ))- })- .collect())+ batch: batch.clone(), slot, job: i,+ });+ }+ }+ }+ Ok(frames)}-pub(crate) struct Frame {- pub(crate) geometry: EvaluatedGeometry,- bind: [wgpu::BindGroup; 3],- params: [wgpu::Buffer; 3],- bounds: wgpu::Buffer,+/// Retained control and scratch storage for evaluations with compatible bindings.+struct Batch {+ bind: wgpu::BindGroup,+ params: wgpu::Buffer,+ scratch: wgpu::Buffer,+ bounds_offset: u64,readback: wgpu::Buffer,+ jobs: Vec<usize>,count: u32,groups: [u32; 2],timed: bool,point_vertices: u32,}+pub(crate) struct Frame {+ pub(crate) geometry: EvaluatedGeometry,+ batch: Arc<Batch>,+ slot: usize,+ job: usize,+}impl Frame {pub(crate) fn append_inputs(&self, changes: &values::ChangeTracker, inputs: &mut Vec<u8>) {- for params in &self.params {- changes.append_buffer_inputs(params, inputs);- }+ changes.append_inputs(values::ChangeKey::Displacement(self.job), inputs);}pub(crate) fn dirty(&self, changes: &values::ChangeTracker) -> bool {- self.params.iter().any(|buffer| {- changes- .uploads- .iter()- .any(|(destination, ..)| destination == buffer)- })+ changes.dirty(values::ChangeKey::DisplacedPositions(self.job))}- pub(crate) fn new(- r: &Renderer,- pipeline: &Pipeline,- mesh: &Mesh,- skin: Option<&FrameDeform>,- geometry: EvaluatedGeometry,+}+impl Batch {+ fn new(r: &Renderer, pipeline: &Pipeline, mesh: &Mesh, jobs: &[usize],+ source: &wgpu::Buffer, source_offset: u64, source_size: u64,+ previous: &wgpu::Buffer, attributes: &wgpu::Buffer,+ topology: &wgpu::Buffer, current: &wgpu::Buffer, endpoints: &wgpu::Buffer,) -> Self {- let buffer = |label, size, usage| {- gpu_memory::buffer(- &r.device,- &wgpu::BufferDescriptor {- label: Some(label),- size,- usage,- mapped_at_creation: false,- },- )- };- let params = std::array::from_fn(|_| {- buffer(- "geometry evaluation parameters",- std::mem::size_of::<Parameters>() as u64,- wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- )+ let buffer = |label, size, usage| gpu_memory::buffer(&r.device, &wgpu::BufferDescriptor {+ label: Some(label), size, usage, mapped_at_creation: false,});- let positions = buffer(- "displaced positions",- u64::from(mesh.count / mesh.point_vertices.max(1)) * 3 * 4 * 3,- wgpu::BufferUsages::STORAGE,- );- let bounds = buffer(- "evaluated bounds",- 32,- wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,- );- let readback = buffer(- "evaluated bounds readback",- 32,- wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,- );- let bind = std::array::from_fn(|pose| {- r.device.create_bind_group(&wgpu::BindGroupDescriptor {- label: Some("material geometry evaluation"),- layout: &pipeline.layout,- entries: &[- entry(0, params[pose].as_entire_binding()),- entry(- 1,- skin.map_or_else(- || mesh.source.as_entire_binding(),- |s| s.output.binding(),- ),- ),- entry(- 2,- skin.map_or(&mesh.source, |s| &s.previous_output)- .as_entire_binding(),- ),- entry(3, mesh.attributes.as_entire_binding()),- entry(4, mesh.topology.as_entire_binding()),- entry(5, positions.as_entire_binding()),- entry(6, geometry.output.binding()),- entry(7, geometry.previous_output.binding()),- entry(8, bounds.as_entire_binding()),- ],- })+ let params = buffer("geometry evaluation table",+ (jobs.len() * 3 * std::mem::size_of::<Parameters>()) as u64,+ wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST);+ let bounds_offset = jobs.len() as u64 * u64::from(mesh.count / mesh.point_vertices.max(1)) * 36;+ let scratch = buffer("geometry scratch and bounds", bounds_offset + jobs.len() as u64 * 32,+ wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC);+ let readback = buffer("evaluated bounds page readback", jobs.len() as u64 * 32,+ wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);+ let bind = r.device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("material geometry batch"), layout: &pipeline.layout,+ entries: &[+ entry(0, params.as_entire_binding()),+ // Skin pools can exceed a storage binding limit. Retain the+ // source range that the deformation owner admitted, not its pool.+ entry(1, wgpu::BindingResource::Buffer(wgpu::BufferBinding {+ buffer: source, offset: source_offset,+ size: std::num::NonZeroU64::new(source_size),+ })),+ entry(2, previous.as_entire_binding()), entry(3, attributes.as_entire_binding()),+ entry(4, topology.as_entire_binding()), entry(5, scratch.as_entire_binding()),+ entry(6, current.as_entire_binding()), entry(7, endpoints.as_entire_binding()),+ ],});let count = mesh.count.div_ceil(constants::DEFORM_GROUP);let width = count.min(r.device.limits().max_compute_workgroups_per_dimension);- let groups = [width, count.div_ceil(width)];- Self {- groups,- geometry,- bind,- params,- bounds,- readback,- count: mesh.count,- timed: mesh.timed,- point_vertices: mesh.point_vertices,- }+ Self { bind, params, scratch, bounds_offset, readback, jobs: jobs.to_vec(), count: mesh.count,+ groups: [width, count.div_ceil(width)], timed: mesh.timed,+ point_vertices: mesh.point_vertices }}}@@ -488,8 +455,11 @@ pub(crate) fn evaluate(return Ok(Vec::new());};let mut bounds = vec![None; s.draws.len()];+ let mut parameters = vec![[Parameters::zeroed(); 3]; frames.len()];+ let mut active = vec![false; frames.len()];for (i, frame) in frames.iter().enumerate() {let Some(frame) = frame else { continue };+ let batch = &frame.batch;let offset = s.roots[s.draws[i].object as usize].time_offset;for pose in 0..3 {let to_stream = s.draws[i]@@ -502,44 +472,54 @@ pub(crate) fn evaluate("material displacement requires an invertible mesh-local frame for draw {i}");let params = Parameters {- count: frame.count,+ count: batch.count,material: objects[s.draws[i].object as usize].material_index[0],- time: if frame.timed { time + offset } else { 0. },- previous_time: if frame.timed {+ time: if batch.timed { time + offset } else { 0. },+ previous_time: if batch.timed {if pose==2 {next_time+offset} else {previous_time + offset}} else {0.},- point_vertices: frame.point_vertices,+ point_vertices: batch.point_vertices,pose: pose as u32,- dispatch_width: frame.groups[0] * constants::DEFORM_GROUP,+ dispatch_width: batch.groups[0] * constants::DEFORM_GROUP,reserved: u32::from(s.draws[i].deform.is_some()),object_header: [objects[s.draws[i].object as usize].metadata[2], 0, 0, 0],to_stream,from_stream,+ addresses: [+ 0, // Source addresses are relative to the bound deformation range.+ (frame.geometry.output.offset / 4) as u32,+ frame.slot as u32 * (batch.count / batch.point_vertices.max(1)) * 9,+ (batch.bounds_offset / 4) as u32 + frame.slot as u32 * 8,+ ],};- changes.upload(&frame.params[pose], 0, bytemuck::bytes_of(¶ms));+ parameters[i][pose] = params;+ }+ // Logical jobs own dirty state, not the shared parameter table. A skin+ // update invalidates only its consumers, even when descriptors share a page.+ let changed = changes.changed(values::ChangeKey::Displacement(i),+ bytemuck::cast_slice(¶meters[i]));+ active[i] = cached_bounds[i].is_none() || changed+ || skin[i].as_ref().is_some_and(|skin|+ changes.buffer_dirty(&skin.params) || changes.buffer_dirty(&skin.previous_params));+ if active[i] { changes.publish(values::ChangeKey::DisplacedPositions(i)); }+ }+ let batches: Vec<_> = frames.iter().flatten().filter(|f| f.slot == 0)+ .map(|f| &*f.batch).filter(|b| b.jobs.iter().any(|&i| active[i])).collect();+ for batch in &batches {+ for (slot, &i) in batch.jobs.iter().enumerate() {+ let mut poses = parameters[i];+ for params in &mut poses {+ params.object_header[1] = u32::from(active[i]);+ }+ // Keep logical dirty subranges even though jobs share one binding.+ // The upload owner merges adjacent changed rows into one copy.+ changes.upload(&batch.params,+ (slot * 3 * std::mem::size_of::<Parameters>()) as u64,+ bytemuck::cast_slice(&poses));}}- let uploaded = |buffer: &wgpu::Buffer| {- changes- .uploads- .iter()- .any(|(destination, ..)| destination == buffer)- };- let active: Vec<bool> = frames- .iter()- .enumerate()- .map(|(i, frame)| {- frame.as_ref().is_some_and(|frame| {- cached_bounds[i].is_none()- || frame.params.iter().any(uploaded)- || skin[i].as_ref().is_some_and(|skin| {- uploaded(&skin.params) || uploaded(&skin.previous_params)- })- })- })- .collect();for (i, frame) in frames.iter().enumerate() {if frame.is_some() && !active[i] {bounds[i] = cached_bounds[i];@@ -582,58 +562,29 @@ pub(crate) fn evaluate(),});pass.set_pipeline(stage);- for pose in 0..if std::ptr::eq(stage, &pipeline.initialize) {- 1- } else {- 3- } {- pass.set_bind_group(- 1,- materials.map_or_else(|| s.material_table.bind(), |m| &m.bind),- &[],- );- for (_, frame) in frames- .iter()- .enumerate()- .filter(|(i, _)| active[*i])- .filter_map(|(i, f)| f.as_ref().map(|f| (i, f)))- {- pass.set_bind_group(2, &frame.bind[pose], &[]);- let groups = if std::ptr::eq(stage, &pipeline.initialize) {- [1, 1]- } else if std::ptr::eq(stage, &pipeline.evaluate) && frame.point_vertices != 0 {- let count = (frame.count / frame.point_vertices).div_ceil(constants::DEFORM_GROUP);- [count.min(frame.groups[0]), count.div_ceil(frame.groups[0])]- } else {- frame.groups- };- pass.dispatch_workgroups(groups[0], groups[1], 1);- }+ pass.set_bind_group(1, materials.map_or_else(|| s.material_table.bind(), |m| &m.bind), &[]);+ for batch in &batches {+ pass.set_bind_group(2, &batch.bind, &[]);+ let initialize = std::ptr::eq(stage, &pipeline.initialize);+ let groups = if initialize { [1, 1] }+ else if std::ptr::eq(stage, &pipeline.evaluate) && batch.point_vertices != 0 {+ let count = (batch.count / batch.point_vertices).div_ceil(constants::DEFORM_GROUP);+ [count.min(batch.groups[0]), count.div_ceil(batch.groups[0])]+ } else { batch.groups };+ pass.dispatch_workgroups(groups[0], groups[1], batch.jobs.len() as u32 * if initialize { 1 } else { 3 });}}- for (_, frame) in frames- .iter()- .enumerate()- .filter(|(i, _)| active[*i])- .filter_map(|(i, f)| f.as_ref().map(|f| (i, f)))- {- encoder.copy_buffer_to_buffer(&frame.bounds, 0, &frame.readback, 0, 32);+ for batch in &batches {+ encoder.copy_buffer_to_buffer(&batch.scratch, batch.bounds_offset, &batch.readback, 0, batch.jobs.len() as u64 * 32);}let submission = crate::command_finish::Segments::submit(&r.queue, encoder);r.errors.check()?;let (send, receive) = std::sync::mpsc::channel();- for (_, frame) in frames- .iter()- .enumerate()- .filter(|(i, _)| active[*i])- .filter_map(|(i, f)| f.as_ref().map(|f| (i, f)))- {+ for batch in &batches {let send = send.clone();- frame- .readback- .map_async(wgpu::MapMode::Read, .., move |result| {- let _ = send.send(result);- });+ batch.readback.map_async(wgpu::MapMode::Read, .., move |result| {+ let _ = send.send(result);+ });}if !active.iter().any(|active| *active) {for (i, draw) in s.draws.iter().enumerate() {@@ -650,24 +601,21 @@ pub(crate) fn evaluate(})};let mut invalid = None;- for (i, frame) in frames.iter().enumerate() {- let Some(frame) = frame else { continue };- if !active[i] {- continue;- }+ for batch in &batches {receive.recv()??;- let bytes = frame.readback.get_mapped_range(..);+ let bytes = batch.readback.get_mapped_range(..);let words: &[u32] = bytemuck::cast_slice(&bytes);- let valid = words[6] == 0;- let minimum = Vec3::new(decode(words[0]), decode(words[1]), decode(words[2]));- let maximum = Vec3::new(decode(words[3]), decode(words[4]), decode(words[5]));- drop(bytes);- frame.readback.unmap();- if valid && minimum.is_finite() && maximum.is_finite() {- bounds[i] = Some((minimum, maximum));- } else {- invalid.get_or_insert(i);+ for (slot, &i) in batch.jobs.iter().enumerate().filter(|(_, i)| active[**i]) {+ let words = &words[slot * 8..][..8];+ let valid = words[6] == 0;+ let minimum = Vec3::new(decode(words[0]), decode(words[1]), decode(words[2]));+ let maximum = Vec3::new(decode(words[3]), decode(words[4]), decode(words[5]));+ if valid && minimum.is_finite() && maximum.is_finite() {+ bounds[i] = Some((minimum, maximum));+ } else { invalid.get_or_insert(i); }}+ drop(bytes);+ batch.readback.unmap();}if let Some(i) = invalid {anyhow::bail!("material displacement produced nonfinite geometry for draw {i}");diff --git a/crates/vork-render/src/display_program.rs b/crates/vork-render/src/display_program.rsindex a473cb0..706e474 100644--- a/crates/vork-render/src/display_program.rs+++ b/crates/vork-render/src/display_program.rs@@ -10,6 +10,7 @@ pub(crate) struct Prepared {words: Vec<u32>,animation: Option<programs::InputAnimation>,sources: Vec<ImageSource>,+ denoise_exposure: Option<usize>,}/// One `Image` input as linear RGBA32F texels.struct ImageData {@@ -62,8 +63,9 @@ pub(crate) fn prepare(let program = programs::cached(r,key,- |p: &DisplayProgram| &p.dependencies,- || Compiler::discover().compile_display(&abi, &source, &origin, &tag[..12]),+ &Compiler::discover(),+ &abi, &source, &origin,+ |compiler| compiler.compile_display(&abi, &source, &origin, &tag[..12]),).with_context(|| format!("render.display: program {name}"))?;if !program.warnings.trim().is_empty() {@@ -117,7 +119,12 @@ pub(crate) fn prepare(Some(name) => programs::InputAnimation::with_discrete(scene, base, name, &program.inputs, &mut words, true)?,None => None,};+ // These bundled displays define exposure in stops before their view transform.+ // A custom display has no implied radiometric contract.+ let denoise_exposure = matches!(name.as_str(), "std/agx" | "std/standard" | "blender/filmic")+ .then(|| program.inputs.fields.iter().find(|f| f.name == "exposure").map(|f| f.offset)).flatten();Ok(Prepared {+ denoise_exposure,animation,program,words,@@ -143,6 +150,34 @@ fn library_image(image: vork_scene::libraries::ProgramImage, executable: Option<mod tests {use super::*;+ #[test]+ #[ignore = "requires real GPU and pinned Slang"]+ fn denoiser_preexposure_uses_only_declared_display_units() -> Result<()> {+ let r = Renderer::new()?;+ for program in ["std/agx", "std/standard", "blender/filmic", "custom"] {+ for exposure in [-5., 0., 17.] {+ let scene: v2::Scene = serde_json::from_value(serde_json::json!({+ "version":2, "nodes":[{"type":"camera"}],+ "render":{"display":{"program":program,"inputs":{"exposure":exposure}}},+ "programs":{"custom":{"source":"struct Inputs {float exposure=0.;}; float3 display(DisplayContext ctx, Inputs i) {return ctx.color;}"}}+ }))?;+ let stage = prepare(&r, &scene, Path::new("."))?.install(&r)?;+ assert_eq!(stage.denoise_scale(0.), if program == "custom" {1.} else {2_f32.powf(exposure)});+ }+ }+ let scene: v2::Scene = serde_json::from_value(serde_json::json!({+ "version":2, "nodes":[{"type":"camera"}],+ "render":{"display":"view", "duration":1},+ "materials":{"view":{"program":"std/standard","inputs":{"exposure":0}}},+ "animation":[{"tracks":[{"path":["materials","view","inputs","exposure"],"keys":[[0,0],[1,4]]}]}]+ }))?;+ let stage = prepare(&r, &scene, Path::new("."))?.install(&r)?;+ assert_eq!(stage.denoise_scale(0.), 1.);+ assert_eq!(stage.denoise_scale(0.5), 4.);+ assert_eq!(stage.denoise_scale(1.), 16.);+ Ok(())+ }+#[test]fn filmic_uses_companion_file_and_reports_expected_path() -> Result<()> {let root = std::env::temp_dir().join(format!("vork-filmic-data-{}", std::process::id()));@@ -205,6 +240,7 @@ pub(crate) struct Stage {words: wgpu::Buffer,images: Vec<wgpu::TextureView>,input_words: Vec<u32>,+ denoise_exposure: Option<usize>,animation: Option<programs::InputAnimation>,}impl Prepared {@@ -401,11 +437,22 @@ fn {sample}(slot:u32,uv:vec2<f32>,dx:vec2<f32>,dy:vec2<f32>)->vec4<f32> {{words,images,input_words: self.words,+ denoise_exposure: self.denoise_exposure,animation: self.animation,})}}impl Stage {+ /// Fixed authored pre-exposure, independent of image statistics. Return to+ /// scene-linear units after filtering, before compositing or float output.+ pub(crate) fn denoise_scale(&self, time: f32) -> f32 {+ let Some(offset) = self.denoise_exposure else { return 1.; };+ let mut words = self.input_words.clone();+ if let Some(animation) = &self.animation { animation.words(time, &mut words); }+ // Keep both the scale and its reciprocal normal in FP32.+ let limit = (1 - f32::MIN_EXP) as f32;+ 2_f32.powf(f32::from_bits(words[offset]).clamp(-limit, limit))+ }pub(crate) fn frame_inputs(&self, r: &Renderer) -> Option<wgpu::Buffer> {self.animation.as_ref()?;Some(init(&r.device, "animated display inputs", bytemuck::cast_slice(&self.input_words),diff --git a/crates/vork-render/src/environment_node.rs b/crates/vork-render/src/environment_node.rsindex e958ecf..7360130 100644--- a/crates/vork-render/src/environment_node.rs+++ b/crates/vork-render/src/environment_node.rs@@ -31,16 +31,16 @@ impl Settings {..} = &node.kind{- let label = format!("node {index} ({:?})", node.name);if let Some(first) = first.as_ref() {- bail!("only one environment is supported; found {first} and {label}");+ crate::warnings::additional_environment(node, first, index);+ } else {+ *first = Some(format!("node {index} ({:?})", node.name));+ *found = Some(Settings {+ source: Some(index),+ material: material.clone(),+ medium: medium.clone(),+ });}- *first = Some(label);- *found = Some(Settings {- source: Some(index),- material: material.clone(),- medium: medium.clone(),- });}visit(&node.children, next, found, scene, first)?;}@@ -144,11 +144,16 @@ mod tests {let input = vork_scene::v2::from_test_value(json!({"version":2,"nodes":[{"type":"light","shape":"environment","name":"world_a"},{"type":"node","children":[{"type":"light","shape":"environment","name":"world_b","energy":0}]}]}),)?;- let error = Settings::from_scene(&input).unwrap_err().to_string();- for expected in ["only one", "world_a", "world_b", "node 0", "node 2"] {- assert!(error.contains(expected), "{error}");- }- assert!(!error.contains("raster"));+ // Launch keeps the first environment and reports each dropped request.+ let collector = crate::warnings::Collector::default();+ let _scope = collector.enter();+ assert_eq!(Settings::from_scene(&input)?.source, Some(0));+ let warnings = collector.snapshot();+ assert_eq!(warnings.len(), 1);+ assert_eq!(warnings[0].code, "additional_environment");+ assert_eq!(warnings[0].requested["node_index"], 2);+ assert_eq!(warnings[0].requested["node"]["name"], "world_b");+ assert!(warnings[0].requested["retained_environment"].as_str().unwrap().contains("world_a"));Ok(())}}diff --git a/crates/vork-render/src/environment_program.rs b/crates/vork-render/src/environment_program.rsindex a1b98fb..7f05ca3 100644--- a/crates/vork-render/src/environment_program.rs+++ b/crates/vork-render/src/environment_program.rs@@ -88,8 +88,9 @@ pub(crate) fn compiled(r: &Renderer, source: &str, origin: &Path) -> Result<Envilet abi = programs::abi();let key = program_key(&abi, source, origin)?;let tag = key.to_hex();- programs::cached(r, key, |p: &EnvironmentProgram| &p.dependencies,- || Compiler::discover().compile_environment(&abi, source, origin, &tag[..12]))+ programs::cached(r, key, &Compiler::discover(),+ &abi, &source, &origin,+ |compiler| compiler.compile_environment(&abi, source, origin, &tag[..12]))}/// Compile (cached) and evaluate an environment program with these input values.@@ -115,7 +116,7 @@ fn bake_animated(let animation = animation_source.map(|(scene, base, name)|programs::InputAnimation::new(scene, base, name, &program.inputs, &mut words)).transpose()?.flatten();let spatial_fallback=program.spatial && animation_source.is_some_and(|(scene,_,_)|scene.media_disabled);- if spatial_fallback { eprintln!("warning: environment {}: ignored spatial origin dependence; evaluating the directional environment at the origin", origin.display()); }+ if spatial_fallback { crate::warnings::dropped("spatial_environment", serde_json::json!({"program":origin,"inputs":values}), format!("warning: environment {}: ignored spatial origin dependence; evaluating the directional environment at the origin", origin.display())); }if program.spatial && !spatial_fallback {ensure!(!program.inputs.fields.iter().any(|f|f.ty==vork_slang::Type::Image),"spatial environments do not yet support image inputs");let (scene,_,material)=animation_source.context("spatial environment requires a scene")?;diff --git a/crates/vork-render/src/forward_variant.rs b/crates/vork-render/src/forward_variant.rsindex 5ab85f4..277037d 100644--- a/crates/vork-render/src/forward_variant.rs+++ b/crates/vork-render/src/forward_variant.rs@@ -273,7 +273,7 @@ pub fn hit_kernel_registers(module: &str, adaptive: bool, probes: bool) -> Vec<Slet mut defines = material_registers(material);defines.push("-DVORK_HIT_KERNEL".to_owned());defines.push(format!("-DVORK_HIT_REGISTER=b{}",material+5+if probes {3} else {0}));- if module == "gi_ray" {defines.push(format!("-DVORK_GI_MEDIUM_REGISTER=u{}",material+6+if probes {3} else {0}));}+ if module == "gi_ray" {defines.push(format!("-DVORK_GI_QUERY_REGISTER=u{}",material+6+if probes {3} else {0}));}if module == "reflections_hits" {defines.push(format!("-DVORK_REFLECTION_FIELDS_REGISTER=b{}",material+6+if probes {3} else {0}));defines.push(format!("-DVORK_REFLECTION_MEDIUM_REGISTER=b{}",material+7+if probes {3} else {0}));diff --git a/crates/vork-render/src/frame.rs b/crates/vork-render/src/frame.rsindex 87deb03..ad9523f 100644--- a/crates/vork-render/src/frame.rs+++ b/crates/vork-render/src/frame.rs@@ -755,7 +755,7 @@ impl FrameSlot {outputs: ReadbackOutputs,) -> Result<()> {if self.propagation_motion && (outputs.motion || outputs.float.motion) && !self.warned_propagation_motion {- eprintln!("warning: ignored image motion under authored curved propagation; motion output is zero, sampled shutter blur is retained");+ crate::warnings::dropped("propagation_motion", serde_json::json!({"channel":"motion","propagation":"curved"}), format!("warning: ignored image motion under authored curved propagation; motion output is zero, sampled shutter blur is retained"));self.warned_propagation_motion=true;}self.gpu_check(r)?;@@ -1338,7 +1338,7 @@ impl FrameSlot {}}if let Some(stage) = &self.view.post.denoiser {- stage.run(r, &mut encoder, self.view.sample_count, &mut self.denoise_ms, &mut self.sample_segments)?;+ stage.run(r, &mut encoder, self.view.sample_count, s.display_program.denoise_scale(frame_time), &mut self.denoise_ms, &mut self.sample_segments)?;}}Pass::Readback => self.ring.encode(&mut encoder, self.view.readback_outputs),@@ -1600,9 +1600,9 @@ impl FrameSlot {}if placement_errors!=0 {fail(self);- anyhow::bail!("computed placement rejected: {}{}",+ return Err(anyhow::anyhow!("computed placement rejected: {}{}",if placement_errors&1!=0 {"live count exceeds installed capacity; "} else {""},- if placement_errors&2!=0 {"nonfinite translation/scale or invalid unit rotation"} else {""});+ if placement_errors&2!=0 {"nonfinite translation/scale or invalid unit rotation"} else {""}).context(crate::failure::FailureKind::Scene));}// The shader reports its largest band's evaluations; the frame estimate// gives every full band of the most finely banded view that many.diff --git a/crates/vork-render/src/import.rs b/crates/vork-render/src/import.rsindex 74f8d52..39a1a87 100644--- a/crates/vork-render/src/import.rs+++ b/crates/vork-render/src/import.rs@@ -777,6 +777,7 @@ mod tests {/// unwraps and `unreachable!` type matches, or vork's bufferView slice; each/// is now an error naming the problem.#[test]+ #[cfg(vork_private_tests)]fn malformed_documents_are_errors() {let seeds = Path::new(env!("CARGO_MANIFEST_DIR")).join("../vork-fuzz/seeds/gltf");for (seed, cause) in [@@ -796,10 +797,12 @@ mod tests {#[test]fn short_accessor_stride_is_an_error() {- let bytes=include_bytes!("../../vork-fuzz/seeds/gltf/short-accessor-stride.gltf");+ let bytes=br#"{"asset":{"version":"2.0"},"buffers":[{"byteLength":12,"uri":"data:application/octet-stream;base64,AAAAAAAAAAAAAAAA"}],"bufferViews":[{"buffer":0,"byteLength":12,"byteStride":4}],"accessors":[{"bufferView":0,"componentType":5126,"count":1,"type":"VEC3","min":[0,0,0],"max":[0,0,0]}],"meshes":[{"primitives":[{"attributes":{"POSITION":0}}]}]}+"#;let error=from_slice(bytes).unwrap_err().to_string();assert!(error.contains("byteStride 4 is smaller than its 12-byte element"),"{error}");- let bytes=include_bytes!("../../vork-fuzz/seeds/gltf/sparse-accessor-stride.gltf");+ let bytes=br#"{"asset":{"version":"2.0"},"buffers":[{"byteLength":16,"uri":"data:application/octet-stream;base64,AAAAAAAAAAAAAAAAAAAAAA=="}],"bufferViews":[{"buffer":0,"byteOffset":0,"byteLength":1},{"buffer":0,"byteOffset":4,"byteLength":12,"byteStride":4}],"accessors":[{"componentType":5126,"count":1,"type":"VEC3","min":[0,0,0],"max":[0,0,0],"sparse":{"count":1,"indices":{"bufferView":0,"componentType":5121},"values":{"bufferView":1}}}],"meshes":[{"primitives":[{"attributes":{"POSITION":0}}]}]}+"#;let error=from_slice(bytes).unwrap_err().to_string();assert!(error.contains("sparse views must not declare byteStride"),"{error}");}diff --git a/crates/vork-render/src/install.rs b/crates/vork-render/src/install.rsindex 844ed28..9a39749 100644--- a/crates/vork-render/src/install.rs+++ b/crates/vork-render/src/install.rs@@ -65,20 +65,30 @@ pub(crate) fn ignore_participating_media(r: &Renderer, scene: &mut Scene, base:clear(&mut node.children, stages, geometry);}}+ let medium_request = serde_json::json!({"sites":sites,"materials":media.iter().filter_map(|name| scene.materials.get(name).map(|m|(name,m))).collect::<std::collections::BTreeMap<_,_>>()});clear(&mut scene.nodes, &stages, &scene.geometry);- fn one_world(nodes:&mut [Node],found:&mut bool,ignored:&mut std::collections::BTreeSet<String>) {+ fn one_world(nodes:&mut [Node],found:&mut Option<String>,ignored:&mut std::collections::BTreeSet<String>,next:&mut usize) {for node in nodes {+ let index = *next; *next += 1;if matches!(node.kind,NodeKind::Light {shape:vork_scene::LightShape::Environment,..}) {- if *found {- eprintln!("warning: ignored additional environment light {:?}; retaining the first environment",node.name);+ if let Some(first) = found.as_ref() {+ crate::warnings::additional_environment(node, first, index);ignored.insert(node.name.clone());node.kind=NodeKind::Node {};- } else {*found=true;}+ } else {*found=Some(format!("node {index} ({:?})", node.name));}}- one_world(&mut node.children,found,ignored);+ one_world(&mut node.children,found,ignored,next);}}let mut ignored_worlds=std::collections::BTreeSet::new();- one_world(&mut scene.nodes,&mut false,&mut ignored_worlds);+ one_world(&mut scene.nodes,&mut None,&mut ignored_worlds,&mut 0);+ // Report the exact authored keys as well as the dropped light itself.+ for layer in &scene.animation {+ for track in layer.tracks.iter().flatten() {+ if matches!(track.path.as_slice(),[root,name,field,..] if root=="nodes" && ignored_worlds.contains(name) && !matches!(field.as_str(),"translation"|"rotation"|"scale"|"visible")) {+ crate::warnings::dropped("additional_environment_track", serde_json::json!({"track":track}), "additional environment light-property animation; retaining the first environment".into());+ }+ }+ }for layer in &mut scene.animation {if let Some(tracks)=&mut layer.tracks {tracks.retain(|t|!matches!(t.path.as_slice(),[root,name,field,..] if root=="nodes" && ignored_worlds.contains(name) && !matches!(field.as_str(),"translation"|"rotation"|"scale"|"visible")));}}@@ -89,10 +99,14 @@ pub(crate) fn ignore_participating_media(r: &Renderer, scene: &mut Scene, base:scene.materials.insert(name.clone(), serde_json::from_value(serde_json::json!({"program":"std/openpbr","inputs":{"geometry_opacity":0}}))?);}for layer in &mut scene.animation {- if let Some(tracks)=&mut layer.tracks { tracks.retain(|t| !(t.path.first().is_some_and(|p|p=="materials") && t.path.get(1).is_some_and(|p|pure.contains(p)))); }+ if let Some(tracks)=&mut layer.tracks { tracks.retain(|t| {+ let dropped = t.path.first().is_some_and(|p|p=="materials") && t.path.get(1).is_some_and(|p|pure.contains(p));+ if dropped { crate::warnings::dropped("participating_media_track", serde_json::json!({"track":t}), "participating-medium material animation; medium transport is disabled".into()); }+ !dropped+ }); }}scene.media_disabled=true;- if !sites.is_empty() { eprintln!("warning: ignored participating media for this release: {}", sites.join(", ")); }+ if !sites.is_empty() { crate::warnings::dropped("participating_media", medium_request, format!("warning: ignored participating media for this release: {}", sites.join(", "))); }Ok(sites)}@@ -1231,7 +1245,7 @@ impl InstalledScene {if let NodeKind::Mesh { geometry, skin, .. } = &node.kind {draw.computed = crate::computed_geometry::dynamic(input, &input.geometry[geometry]);if draw.computed && (skin.is_some() || materials[draw.material].record.extra[1]>0. || materials[draw.material].transmissive) {- eprintln!("warning: node {:?}: ignored computed geometry updates combined with skinning, opacity or transmission; using authored geometry",node.name);+ crate::warnings::dropped("computed_geometry", serde_json::json!({"node":node}), format!("warning: node {:?}: ignored computed geometry updates combined with skinning, opacity or transmission; using authored geometry",node.name));draw.computed=false;}}@@ -1868,7 +1882,7 @@ impl InstalledScene {.copied().unwrap_or(u64::from(vertex));if let Some(&material) = assignments.get(&identity) {if material!=draw.material && displacement_seam_nodes.insert(roots[draw.object as usize].node) {- eprintln!("warning: node {:?}: ignored conflicting displacement materials on shared geometry",nodes[roots[draw.object as usize].node].node.name);+ crate::warnings::dropped("conflicting_displacement", serde_json::json!({"node":nodes[roots[draw.object as usize].node].node}), format!("warning: node {:?}: ignored conflicting displacement materials on shared geometry",nodes[roots[draw.object as usize].node].node.name));}}if displaced_pass { assignments.insert(identity, draw.material); }@@ -1936,7 +1950,7 @@ impl InstalledScene {let key = (root.node, root.instance_index, draw.gltf_node.0, identity);if let Some(before) = displacement_seams.insert(key, values.clone()) {if before!=values && displacement_seam_nodes.insert(root.node) {- eprintln!("warning: node {:?}: ignored displacement across inconsistent attributes at shared vertex {identity}",nodes[root.node].node.name);+ crate::warnings::dropped("displacement_attributes", serde_json::json!({"node":nodes[root.node].node,"vertex":identity}), format!("warning: node {:?}: ignored displacement across inconsistent attributes at shared vertex {identity}",nodes[root.node].node.name));}}}@@ -1952,7 +1966,7 @@ impl InstalledScene {let point_normal=draw.exit_geometry.as_ref().is_some_and(|g|!g.point_centers.is_empty()) && programs.as_ref().unwrap().displacement_uses_normal(records[draw.material].tag[0]);if displacement_seam_nodes.contains(&roots[draw.object as usize].node) {continue;}if draw.computed || implicit || point_normal {- eprintln!("warning: node {:?}: ignored displacement on computed/implicit geometry or points using NORMAL",node.name);+ crate::warnings::dropped("displacement_geometry", serde_json::json!({"node":node}), format!("warning: node {:?}: ignored displacement on computed/implicit geometry or points using NORMAL",node.name));continue;}ensure!(@@ -2053,7 +2067,7 @@ impl InstalledScene {.filter_map(|(i, node)| {if !crate::compute::places_instances(input,&node.node) {return None;}if draws.iter().any(|d| roots[d.object as usize].node==i && materials[d.material].transparent) {- eprintln!("warning: node {:?}: ignored computed instance placement on transparent material; using authored placements",node.node.name);+ crate::warnings::dropped("computed_instances", serde_json::json!({"node":node.node}), format!("warning: node {:?}: ignored computed instance placement on transparent material; using authored placements",node.node.name));None} else {Some(i)}})diff --git a/crates/vork-render/src/lib.rs b/crates/vork-render/src/lib.rsindex 0d8f37c..6a6c612 100644--- a/crates/vork-render/src/lib.rs+++ b/crates/vork-render/src/lib.rs@@ -6,6 +6,8 @@//! compiles the pass order; frame.rs owns FrameSlot and walks it; values.rs//! prepares per-frame values;//! passes/ encodes each GPU pass.+mod warnings;+pub use warnings::RenderWarning;mod polygon;mod subdivision;mod displacement;@@ -399,6 +401,7 @@ impl Renderer {}fn finish_shader_warmup(&self) -> Result<()> {+ vork_slang::progress::phase("Setup: finishing driver pipelines and saving cache", 0);self.settle_pipelines()?;if self.cache.is_some() {let saved = self.saved.lock().unwrap();@@ -418,49 +421,64 @@ impl Renderer {}/// Report actual device/tool availability before warming shaders.- pub fn setup_report(&self) -> Result<()> {+ pub fn setup_report(&self, out: &mut impl std::io::Write) -> Result<()> {+ macro_rules! report {+ ($($arg:tt)*) => { writeln!(out, $($arg)*)? };+ }let driver = self.adapter_info.driver_info.trim();if driver.is_empty() {- println!("GPU: {} ({:?}; driver version not reported)", self.adapter_info.name, self.adapter_info.backend);+ report!("GPU: {} ({:?}; driver version unavailable through the graphics API; this does not indicate a missing driver)", self.adapter_info.name, self.adapter_info.backend);} else {- println!("GPU: {} ({:?}; driver {driver})", self.adapter_info.name, self.adapter_info.backend);+ report!("GPU: {} ({:?}; driver {driver})", self.adapter_info.name, self.adapter_info.backend);}if self.adapter_info.device_type == wgpu::DeviceType::Cpu {- println!("GPU: software rendering on the CPU; expect slow renders. Install your GPU vendor's Vulkan driver for hardware rendering.");+ report!("GPU: software rendering on the CPU; expect slow renders. Install your GPU vendor's Vulkan driver for hardware rendering.");}- println!("Ray queries: {}", if self.device.features().contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) { "available; the renderer can select scene queries" } else { "unavailable; profiles refuse effects that need scene queries" });+ report!("Ray queries: {}", if self.device.features().contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) { "available; the renderer can select scene queries" } else { "unavailable; profiles refuse effects that need scene queries" });let mut failures = Vec::new();match vork_slang::Compiler::discover().version() {- Ok(version) => println!("Slang: {version} ready"),- Err(error) => { println!("Slang: {error:#}. Reinstall the complete vork archive or set VORK_SLANGC to the pinned slangc."); failures.push("Slang"); }+ Ok(version) => report!("Slang: {version} ready"),+ Err(error) => { report!("Slang: {error:#}. Reinstall the complete vork archive or set VORK_SLANGC to the pinned slangc."); failures.push("Slang"); }}match denoise::open_fast(self) {- Ok(()) => println!("Denoiser: OIDN on the GPU ({})", self.adapter_info.name),+ Ok(()) => report!("Denoiser: OIDN on the GPU ({})", self.adapter_info.name),Err(reason) => match denoise::check_runtime() {- Ok(()) => println!("Denoiser: no fast GPU denoiser for {} ({reason}). std/draft and std/final turn denoising off and use more samples; --set denoise=true uses the slow CPU denoiser.", self.adapter_info.name),- Err(error) => { println!("Denoiser: {error:#}. Reinstall the complete archive, or set VORK_OIDN to the OIDN 2.5.1 library."); println!("Rendering will continue without OIDN; std/draft and std/final use more samples."); }+ Ok(()) => report!("Denoiser: no fast GPU denoiser for {} ({reason}). std/draft and std/final turn denoising off and use more samples; --set denoise=true uses the slow CPU denoiser.", self.adapter_info.name),+ Err(error) => { report!("Denoiser: {error:#}. Reinstall the complete archive, or set VORK_OIDN to the OIDN 2.5.1 library."); report!("Rendering will continue without OIDN; std/draft and std/final use more samples."); }}}if cfg!(target_os = "linux") {- println!("Video: native NVENC is attempted on NVIDIA; otherwise ffmpeg readback encoding. Encoder initialization is checked when opening a video output.");+ report!("Video: native NVENC is attempted on NVIDIA; FFmpeg readback encoding is the fallback. Native encoder initialization is checked when opening video output.");+ }+ if cfg!(target_os = "windows") {+ report!("Video: FFmpeg NVENC after readback when usable; otherwise software libx264. MOV uses software prores_ks.");}if cfg!(target_os = "macos") {- println!("Video: system VideoToolbox for MP4; MOV may need ffmpeg prores_ks as fallback.");+ report!("Video: system VideoToolbox for MP4; MOV may need ffmpeg prores_ks as fallback.");}match std::process::Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output() {Ok(output) if output.status.success() => {let listing = String::from_utf8_lossy(&output.stdout);- println!("FFmpeg: {}; {}", if listing.contains("libx264") { "libx264 fallback available" } else if cfg!(target_os = "macos") { "libx264 fallback absent (optional; native VideoToolbox MP4 needs no FFmpeg)" } else { "WARNING: libx264 missing; install ffmpeg with libx264 (Windows: ffmpeg-release-essentials.zip from https://www.gyan.dev/ffmpeg/builds/) and add bin to PATH" }, if cfg!(target_os = "linux") { "required for MP4 muxing, including native NVENC" } else if cfg!(target_os = "macos") { "optional for native VideoToolbox MP4" } else { "required for MP4/MOV" });- println!("MOV: {}", if listing.contains("prores_ks") { "ffmpeg prores_ks available" } else { "prores_ks unavailable; install an ffmpeg build with prores_ks" });+ if cfg!(any(target_os = "linux", target_os = "windows")) && listing.contains("h264_nvenc") {+ match vork_encode::probe_ffmpeg_nvenc(256, 256) {+ Ok(()) => report!("FFmpeg NVENC: initialization ready"),+ Err(error) => {+ report!("FFmpeg NVENC: unusable with this driver; readback MP4 falls back to software libx264 if installed. Update the NVIDIA driver or install a compatible FFmpeg build. {error:#}");+ if cfg!(target_os = "linux") { report!("Native NVENC: checked separately at video output initialization; FFmpeg's NVENC API mismatch does not disable the native encoder."); }+ }+ }+ }+ report!("FFmpeg: {}; {}", if listing.contains("libx264") { "libx264 fallback available" } else if cfg!(target_os = "macos") { "libx264 fallback absent (optional; native VideoToolbox MP4 needs no FFmpeg)" } else { "WARNING: libx264 missing; install ffmpeg with libx264 (Windows: ffmpeg-release-essentials.zip from https://www.gyan.dev/ffmpeg/builds/) and add bin to PATH" }, if cfg!(target_os = "linux") { "required for MP4 muxing, including native NVENC" } else if cfg!(target_os = "macos") { "optional for native VideoToolbox MP4" } else { "required for MP4/MOV" });+ report!("MOV: {}", if listing.contains("prores_ks") { "ffmpeg prores_ks available" } else { "prores_ks unavailable; install an ffmpeg build with prores_ks" });}- _ if cfg!(target_os = "macos") => println!("Video: native VideoToolbox MP4 is ready without FFmpeg; MOV fallback needs ffmpeg prores_ks (brew install ffmpeg). Encoder availability is checked when opening video output."),- _ => println!("FFmpeg: missing or unusable; required for MP4/MOV, including Linux native NVENC muxing. Install ffmpeg (Ubuntu: sudo apt install ffmpeg; Windows: winget install Gyan.FFmpeg, or extract ffmpeg-release-essentials.zip from https://www.gyan.dev/ffmpeg/builds/ and add its bin folder to PATH). PNG/EXR remain available."),+ _ if cfg!(target_os = "macos") => report!("FFmpeg: missing or unusable; native VideoToolbox MP4 is ready without FFmpeg; MOV fallback needs ffmpeg prores_ks (brew install ffmpeg). Encoder availability is checked when opening video output."),+ _ => report!("FFmpeg: missing or unusable; required for MP4/MOV, including Linux native NVENC muxing. Install ffmpeg (Ubuntu: sudo apt install ffmpeg; Windows: winget install Gyan.FFmpeg, or extract ffmpeg-release-essentials.zip from https://www.gyan.dev/ffmpeg/builds/ and add its bin folder to PATH). PNG/EXR remain available."),}- println!("Cache: {}", self.cache_path.parent().unwrap_or(&self.cache_path).display());+ report!("Cache: {}", self.cache_path.parent().unwrap_or(&self.cache_path).display());match self.pipeline_cache_status {- "unsupported" if self.adapter_info.backend == wgpu::Backend::Metal => println!("Pipeline cache: managed by the Metal driver; setup warms it. Compiled shader assets use the cache above."),- "unsupported" => println!("Pipeline cache: driver does not expose persistent pipeline caching; compiled shader assets still use the cache above."),- status => println!("Pipeline cache: {status} for this build and GPU driver"),+ "unsupported" if self.adapter_info.backend == wgpu::Backend::Metal => report!("Pipeline cache: managed by the Metal driver; setup warms it. Compiled shader assets use the cache above."),+ "unsupported" => report!("Pipeline cache: driver does not expose persistent pipeline caching; compiled shader assets still use the cache above."),+ status => report!("Pipeline cache: {status} for this build and GPU driver"),}anyhow::ensure!(failures.is_empty(), "setup tools failed: {}; follow the fixes above", failures.join(", "));Ok(())@@ -942,6 +960,9 @@ impl Renderer {rt::resolve_reflections(&mut scene);rt::resolve_refraction(&mut scene, self.adapter_info.device_type, self.device.features());validate(&scene)?;+ // Capability admission follows release normalization; loading must not+ // reject requests that installation deliberately warns about and drops.+ lights::validate_visibility(&scene)?;animation::fold_material_inputs(&mut scene, base)?;if scene.propagation.is_some() && !scene.render.settings.integrator.is_path() {eprintln!("warning: authored curved propagation uses std/path transport for this scene and its render-image captures");@@ -951,7 +972,7 @@ impl Renderer {if !scene.render.settings.integrator.is_path() && camera_program::scene_spectral(self,&scene,base)? {rt::promote_indirect_to_path(&mut scene);}if scene.render.settings.integrator.denoiser().is_some() {if let Err(error) = denoise::ensure_runtime(self) {- eprintln!("warning: OIDN unavailable; rendering without denoising: {error:#}. Keep the bundled oidn runtime beside vork, or use --set denoise=false.");+ crate::warnings::dropped("denoiser_unavailable", serde_json::json!({"denoise":true}), format!("warning: OIDN unavailable; rendering without denoising: {error:#}. Keep the bundled oidn runtime beside vork, or use --set denoise=false."));scene.render.settings.disable_denoiser();}}@@ -1029,7 +1050,6 @@ impl Renderer {/// Scene validation plus the checks for options this renderer does not implement yet.pub fn validate(scene: &Scene) -> Result<()> {scene.validate()?;- lights::validate_visibility(scene)?;buffers::validate_attributes(scene)?;attributes::names(scene)?;// One environment, without light links (not implemented yet).@@ -1324,9 +1344,13 @@ fn metal_contract_renderer() -> Result<Renderer> {Ok(renderer)}-/// GPU tests skip only adapter discovery failure; device and renderer errors still fail.+/// GPU execution is explicit; after opting in, only adapter discovery failure skips.#[cfg(test)]fn test_renderer() -> Result<Option<Renderer>> {+ if std::env::var("VORK_GPU_TESTS").as_deref() != Ok("1") {+ eprintln!("SKIP GPU test: set VORK_GPU_TESTS=1 with a supported GPU and pinned Slang; see vork help build");+ return Ok(None);+ }match Renderer::new() {Ok(renderer) => Ok(Some(renderer)),Err(error)@@ -1390,29 +1414,38 @@ mod scene_error_context_tests {let default = vork_scene::Profile::load(vork_scene::DEFAULT_PROFILE)?;let resolved = super::load_with_settings(&path, vork_scene::test_settings(&default.resolve(&Default::default())?, &explicit)?, &default.name, None);let authored = super::load_authored(&path);- let rejected = super::load_with_settings(&path, vork_scene::test_settings(&default.resolve(&Default::default())?, serde_json::json!({"refraction":"environment"}).as_object().unwrap())?, &default.name, None);+ let deferred = super::load_with_settings(&path, vork_scene::test_settings(&default.resolve(&Default::default())?, serde_json::json!({"refraction":"environment"}).as_object().unwrap())?, &default.name, None);let repaired = super::load_with_settings(&path, vork_scene::test_settings(&default.resolve(&Default::default())?, serde_json::json!({"refraction":"environment"}).as_object().unwrap())?, &default.name, Some(|scene, _| {scene.nodes[1].visibility.transmission = true;Ok(())}));std::fs::remove_file(&path)?;std::fs::remove_file(&profile.name)?;- resolved?;+ assert!(super::rt::ray_refraction(&resolved?));authored?;- assert!(rejected.is_err());- repaired?; // Edits still precede renderer checks that remain errors at launch.+ // Loading preserves requests; installation checks capabilities after+ // release normalization. The resolved profile still reaches the edit.+ let deferred = deferred?;+ assert!(!deferred.nodes[1].visibility.transmission);+ assert!(!super::rt::ray_refraction(&deferred));+ assert!(!deferred.media_disabled);+ // Loading leaves installation-time capability checks deferred.+ assert!(super::lights::validate_visibility(&deferred).is_err());+ let repaired = repaired?;+ assert!(repaired.nodes[1].visibility.transmission);+ super::lights::validate_visibility(&repaired)?;Ok(())}#[test]- fn renderer_validation_retains_the_scene_filename() {- let path = std::env::temp_dir().join(format!("vork-invalid-transmission-mask-{}.json", std::process::id()));+ fn scene_validation_retains_the_scene_filename() {+ let path = std::env::temp_dir().join(format!("vork-invalid-resolution-{}.json", std::process::id()));vork_scene::v2::write_authored(&path, &serde_json::json!({"version":2,"nodes":[{"type":"camera"},{"type":"node","visible_transmission":false}],- "render":{"settings":{"integrator":"raster","refraction":"environment"}}})).unwrap();+ "render":{"resolution":[0,1080],"settings":{"integrator":"raster","refraction":"environment"}}})).unwrap();let error = format!("{:#}", super::load_authored(&path).unwrap_err());std::fs::remove_file(&path).unwrap();std::fs::remove_file(path.with_file_name(format!("{}.profile.json", path.file_stem().unwrap().to_string_lossy()))).unwrap();assert!(error.contains(path.to_str().unwrap()), "{error}");- assert!(error.contains("visible_transmission"), "{error}");+ assert!(error.contains("positive dimensions"), "{error}");}}diff --git a/crates/vork-render/src/lights.rs b/crates/vork-render/src/lights.rsindex 552e4f1..84c1ba5 100644--- a/crates/vork-render/src/lights.rs+++ b/crates/vork-render/src/lights.rs@@ -256,7 +256,7 @@ pub(super) fn import(let lens = match camera.projection() {gltf::camera::Projection::Perspective(p) => {let far = p.zfar();- if far.is_none() {eprintln!("warning: camera {name}: ignored infinite far clip; using the camera default");}+ if far.is_none() {crate::warnings::dropped("camera_far_clip", serde_json::json!({"camera":name,"clip_end":"infinite"}), format!("warning: camera {name}: ignored infinite far clip; using the camera default"));}let mut inputs=serde_json::json!({"lens":24. / (2. * (p.yfov() * 0.5).tan()),"fit":"vertical","clip_start":p.znear()});if let Some(far)=far {inputs["clip_end"]=far.into();}inputs@@ -264,7 +264,7 @@ pub(super) fn import(gltf::camera::Projection::Orthographic(o) => {let mut inputs=serde_json::json!({"projection":"ortho", "fit":"vertical", "ortho_scale":2. * o.ymag(),"clip_end":o.zfar()});if o.znear()>0. {inputs["clip_start"]=o.znear().into();}- else {eprintln!("warning: camera {name}: ignored zero near clip; using the camera default");}+ else {crate::warnings::dropped("camera_near_clip", serde_json::json!({"camera":name,"clip_start":0}), format!("warning: camera {name}: ignored zero near clip; using the camera default"));}inputs}};@@ -516,7 +516,7 @@ pub(crate) fn validate_visibility(scene: &::vork_scene::v2::Scene) -> Result<()>for node in nodes {let transmission=inherited && node.visibility.transmission;if matches!(node.kind,NodeKind::Light {..}) && (!transmission || !node.visibility.shadow) {- eprintln!("warning: light {:?}: ignored visible_shadow/visible_transmission contribution masks; use shadowed_by or supported light visibility fields",node.name);+ crate::warnings::dropped("light_visibility", serde_json::json!({"node":node,"inherited_transmission":inherited}), format!("warning: light {:?}: ignored visible_shadow/visible_transmission contribution masks; use shadowed_by or supported light visibility fields",node.name));}ignored(&node.children,transmission);}@@ -525,7 +525,7 @@ pub(crate) fn validate_visibility(scene: &::vork_scene::v2::Scene) -> Result<()>for target in scene.track_targets()?.into_iter().flatten() {if let ::vork_scene::TrackTarget::Node {node,property: ::vork_scene::NodeProperty::Visibility(::vork_scene::Ray::Shadow|::vork_scene::Ray::Transmission)}=target {fn light(nodes:&[::vork_scene::v2::Node],name:&str)->bool {nodes.iter().any(|n|n.name==name && matches!(n.kind,NodeKind::Light {..}) || light(&n.children,name))}- if light(&scene.nodes,&node) {eprintln!("warning: light {node:?}: ignored shadow/transmission visibility track");}+ if light(&scene.nodes,&node) {crate::warnings::dropped("light_visibility_track", serde_json::json!({"node":node,"tracks":scene.animation}), format!("warning: light {node:?}: ignored shadow/transmission visibility track"));}}}return Ok(());diff --git a/crates/vork-render/src/materials.rs b/crates/vork-render/src/materials.rsindex a8404a6..debda32 100644--- a/crates/vork-render/src/materials.rs+++ b/crates/vork-render/src/materials.rs@@ -1838,7 +1838,7 @@ pub(crate) fn load_cached(decoders.finish()?;let gltf::Gltf { document, blob } = import::open(path)?;for warning in gltf_extension_warnings(&document) {- eprintln!("glTF {}: {warning}", path.display());+ crate::warnings::dropped("gltf_extension", serde_json::json!({"file":path,"extension":warning.split(':').next(),"materials":document.materials().filter_map(|m| m.extensions().map(|e|serde_json::json!({"index":m.index(),"name":m.name(),"extensions":e}))).collect::<Vec<_>>(),"primitive_variants":document.meshes().flat_map(|m|m.primitives()).filter_map(|p|p.extension_value("KHR_materials_variants").cloned()).collect::<Vec<_>>()}), warning);}let base = path.parent().unwrap_or(Path::new("./"));let buffers = std::sync::Arc::new(import::buffers(&document, Some(base), blob)?);@@ -2353,7 +2353,7 @@ pub(crate) fn openpbr_values(let mut b = RecordBuilder::openpbr();let default_material = ::vork_scene::v2::Material {program: "std/openpbr".into(),- inputs: [("specular_roughness".into(), Input::Number(0.5))].into(),+ inputs: Default::default(),double_sided: true,opacity: None,};diff --git a/crates/vork-render/src/medium.rs b/crates/vork-render/src/medium.rsindex bb751ca..90f2cbf 100644--- a/crates/vork-render/src/medium.rs+++ b/crates/vork-render/src/medium.rs@@ -212,8 +212,9 @@ pub(crate) fn compiled(r: &Renderer, source: &str, origin: &Path) -> Result<Mediprograms::cached(r,key,- |p: &MediumProgram| &p.dependencies,- || Compiler::discover().compile_medium(&abi, source, origin, &tag[..12]),+ &Compiler::discover(),+ &abi, &source, &origin,+ |compiler| compiler.compile_medium(&abi, source, origin, &tag[..12]),)}diff --git a/crates/vork-render/src/native.rs b/crates/vork-render/src/native.rsindex 09a22e9..be1473c 100644--- a/crates/vork-render/src/native.rs+++ b/crates/vork-render/src/native.rs@@ -486,19 +486,17 @@ pub(crate) mod tests {}#[test]- fn gi_medium_accumulation_preserves_native_binding_slots() {+ fn gi_accumulation_preserves_native_binding_slots() {let globals=crate::rt::gi_entries();let materials=crate::pipelines::material_entries(true);- for probes in [false,true] {for medium in [false,true] {+ for probes in [false,true] {let read=if probes {crate::probes::read_entries(0,ShaderStages::COMPUTE).to_vec()} else {vec![]};- let hits=crate::rt::gi_read_entries(medium);+ let hits=crate::rt::gi_read_entries();let slots=metal_slots(&[&globals,&materials,&read,&hits],ShaderStages::COMPUTE);let registers=crate::forward_variant::hit_kernel_registers("gi_ray",false,probes);- assert_eq!(hits.len(),if medium {2} else {1});- if medium {- let slot=slots.iter().find(|s|s.0==3 && s.1==1).unwrap().3;- assert!(registers.contains(&format!("-DVORK_GI_MEDIUM_REGISTER=u{slot}")));- }- }}+ assert_eq!(hits.len(),2);+ let slot=slots.iter().find(|s|s.0==3 && s.1==1).unwrap().3;+ assert!(registers.contains(&format!("-DVORK_GI_QUERY_REGISTER=u{slot}")));+ }}// Exported resource accessors can leave false-positive "used" flags in@@ -795,7 +793,8 @@ pub(crate) mod tests {]);let ray_material = material_entries(true);let gi = crate::rt::gi_entries();- let gi_groups: &[&[BindGroupLayoutEntry]] = &[&gi, &ray_material, &[], &hits];+ let gi_hits = crate::rt::gi_read_entries();+ let gi_groups: &[&[BindGroupLayoutEntry]] = &[&gi, &ray_material, &[], &gi_hits];checked.push((&GI_RAY_COMPUTE, gi_groups));let probe_update = crate::probes::update_entries();let probe_read = crate::probes::read_entries(0, ShaderStages::COMPUTE);@@ -842,7 +841,11 @@ pub(crate) mod tests {_=>unreachable!(),};let reads_probes=*probes || matches!(family,SurfaceKernel::Probes|SurfaceKernel::Directional);- let geometry=if *family==SurfaceKernel::Reflections {reflection_fields.clone()} else {hits.to_vec()};+ let geometry=match family {+ SurfaceKernel::Reflections=>reflection_fields.clone(),+ SurfaceKernel::Gi=>gi_hits.clone(),+ _=>hits.to_vec(),+ };vec![entries,ray_material.clone(),if reads_probes {probe_read.to_vec()} else {vec![]},geometry]}}).collect();diff --git a/crates/vork-render/src/passes/ao.rs b/crates/vork-render/src/passes/ao.rsindex 0968cc8..545b5f2 100644--- a/crates/vork-render/src/passes/ao.rs+++ b/crates/vork-render/src/passes/ao.rs@@ -4,8 +4,10 @@ use wgpu::util::DeviceExt;/// Retain one GI hit-shading specialization over every installed material.pub(crate) fn ray_pipeline(r: &Renderer, cached: &crate::pipelines::CachedPipelines, features: crate::forward_variant::FeatureMask, probes: bool, mode: &crate::pipelines::VariantCompile) -> Result<wgpu::ComputePipeline> {let kernel=cached.drawn_kernel(crate::pipelines::ProgramKernel::Gi { features }, mode,&r.compiler);+ #[cfg(test)]+ r.compiler.hit_selections.lock().unwrap().push((crate::pipelines::ProgramKernel::Gi { features },kernel));let (module, entry)=cached.program_kernel(kernel)?;- let layout=crate::rt::gi_layout(&r.device,&cached.mat_layout,probes,cached.resolve_native.is_some());+ let layout=crate::rt::gi_layout(&r.device,&cached.mat_layout,probes);let pipeline=r.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {label:Some("ray-traced diffuse indirect"),layout:Some(&layout),module:&module,entry_point:Some(entry),compilation_options:Default::default(),cache:r.cache.as_ref(),@@ -14,6 +16,23 @@ pub(crate) fn ray_pipeline(r: &Renderer, cached: &crate::pipelines::CachedPipeliOk(pipeline)}+#[cfg(test)]+thread_local! {+ static TEST_GI_LIMIT: std::cell::Cell<Option<u64>> = const {std::cell::Cell::new(None)};+ static TEST_GI_BYTES: std::cell::Cell<u64> = const {std::cell::Cell::new(0)};+}++// Retain complete rows, reusing their records only after every ray batch finishes.+fn accumulation_band(limits: &wgpu::Limits, width: u32, height: u32) -> Result<(u32, u64)> {+ let row = u64::from(width) * constants::GI_QUERY_BYTES;+ gpu_memory::storage_binding(limits, "GI prepared queries: one row", row)?;+ let rows = (limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) / row)+ .min(u64::from(height)) as u32;+ let bytes = row * u64::from(rows);+ gpu_memory::storage_binding(limits, "GI prepared queries and accumulation", bytes)?;+ Ok((rows, bytes))+}+pub(crate) struct Resources {pub output: wgpu::TextureView,pub incident: wgpu::TextureView,@@ -74,21 +93,36 @@ impl Resources {1,];let frame_rays = rays.context("diffuse GI needs the scene TLAS")?;- let medium=s.pipelines.resolve_native.is_some();- let batch=vork_slang::registry::MEDIUM_GI_RAY_BATCH;- let batches=if medium {(visibility_samples.max(1)*constants::GI_RAYS_PER_SAMPLE).div_ceil(batch)} else {1};- let hits=if medium {- let accumulation=s.transients.buffer(d,"GI medium prepared queries and accumulation",u64::from(aw)*u64::from(ah)*constants::GI_MEDIUM_QUERY_BYTES,wgpu::BufferUsages::STORAGE);+ let batch=vork_slang::registry::GI_RAY_BATCH;+ let batches=(visibility_samples.max(1)*constants::GI_RAYS_PER_SAMPLE).div_ceil(batch);+ let limits = d.limits();+ #[cfg(test)]+ let limits = TEST_GI_LIMIT.with(|cap| {+ let mut limits=limits;+ if let Some(bytes)=cap.get() {limits.max_storage_buffer_binding_size=bytes;}+ limits+ });+ let (band_rows, accumulation_bytes) = accumulation_band(&limits, aw, ah)?;+ let bands = ah.div_ceil(band_rows);+ let hits={+ let accumulation=s.transients.buffer(d,"GI prepared queries and accumulation",accumulation_bytes,wgpu::BufferUsages::STORAGE);+ #[cfg(test)]+ TEST_GI_BYTES.with(|bytes|bytes.set(accumulation.size()));let geometry=frame_rays.hit_bindings();d.create_bind_group(&wgpu::BindGroupDescriptor {- label:Some("GI hit and accumulation buffers"),layout:&crate::rt::gi_read_layout(d,true),+ label:Some("GI hit and accumulation buffers"),layout:&crate::rt::gi_read_layout(d),entries:&[entry(0,wgpu::BindingResource::BufferArray(&geometry)),entry(1,accumulation.as_entire_binding())],})- } else {frame_rays.hits_bind(d)};- let mut source_words=vec![0u32;if medium {batches as usize*64} else {4}];+ };+ let mut source_words=vec![0u32;(bands*batches) as usize*64];let topology=s.rays.as_ref().unwrap();- for i in 0..batches {source_words[i as usize*64..i as usize*64+4].copy_from_slice(&[topology.emitters,topology.implicit[2],topology.implicit[3],0]);}- if medium {for i in 0..batches {source_words[i as usize*64+4]=i*batch;}}+ for band in 0..bands {+ for batch_index in 0..batches {+ let at=((band*batches+batch_index)*64) as usize;+ source_words[at..at+4].copy_from_slice(&[topology.emitters,topology.implicit[2],topology.implicit[3],0]);+ source_words[at+4..at+8].copy_from_slice(&[batch_index*batch,band*band_rows,(ah-band*band_rows).min(band_rows),0]);+ }+ }let sources=d.create_buffer_init(&wgpu::util::BufferInitDescriptor {label:Some("diffuse source topology"),contents:bytemuck::cast_slice(&source_words),@@ -143,10 +177,11 @@ impl Resources {stages.push(reconstruction(s.pipelines.ao_blur_horizontal_pipeline.get(),"AO horizontal blur",false));stages.push(reconstruction(s.pipelines.ao_blur_vertical_pipeline.get(),"AO vertical blur",true));for (pipeline, label, entries, material) in stages {+ for band in 0..if material.is_some() {bands} else {1} {for batch in 0..if material.is_some() {batches} else {1} {let mut entries=entries.clone();if material.is_some() {- entries.iter_mut().find(|e|e.binding==17).unwrap().resource=wgpu::BindingResource::Buffer(wgpu::BufferBinding {buffer:&sources,offset:u64::from(batch)*256,size:std::num::NonZeroU64::new(if medium {32} else {16})});+ entries.iter_mut().find(|e|e.binding==17).unwrap().resource=wgpu::BindingResource::Buffer(wgpu::BufferBinding {buffer:&sources,offset:u64::from(band*batches+batch)*256,size:std::num::NonZeroU64::new(32)});}let pipeline = pipeline.context("incomplete installed AO plan")?;let bind = d.create_bind_group(&wgpu::BindGroupDescriptor {@@ -154,7 +189,8 @@ impl Resources {layout: &pipeline.get_bind_group_layout(0),entries: &entries,});- let mut dispatch = crate::graph::Dispatch::new(pipeline, bind, groups);+ let dispatch_groups = if material.is_some() {[groups[0],(ah-band*band_rows).min(band_rows).div_ceil(8),1]} else {groups};+ let mut dispatch = crate::graph::Dispatch::new(pipeline, bind, dispatch_groups);if material.is_some() {// Ray GI hits read the irradiance volume for further bounces.let probes = (s.plan.effects.ray_indirect).then(|| s.probes.as_ref().map(|p| p.read_bind(d))).flatten();@@ -165,6 +201,7 @@ impl Resources {None => dispatch,});}+ }}}if !dispatches.is_empty() {@@ -247,3 +284,68 @@ mod prepared_query_tests {Ok(())}}++#[cfg(test)]+mod accumulation_tests {+ use super::*;+ #[test]+ fn gi_bands_preserve_float_output_with_independent_storage_limit() -> Result<()> {+ // Adapter-free runners skip with test_renderer's diagnostic; renderer+ // failures and every pixel/allocation assertion still fail on a GPU.+ let Some(r)=crate::test_renderer()? else {return Ok(())};+ let mut scene=crate::test_scene(serde_json::json!({"version":2,+ "render":{"resolution":[66,50]},+ "nodes":[+ {"type":"mesh","geometry":{"std":"sphere"},"materials":[{"inputs":{"base_color":[0.2,0.4,0.7]}}]},+ {"type":"mesh","translation":[0,-1,0],"geometry":{"std":"grid","size":[8,8]}},+ {"type":"camera","translation":[3,2,5],"target":[0,0,0]},+ {"type":"light","shape":"environment","color":[0.4,0.6,0.8]},+ {"type":"light","shape":"rectangle","translation":[-3,5,4],"target":[0,0,0],"energy":500,"size":3}+ ]}),Path::new("."))?;+ scene.render.settings=vork_scene::v2::Profile::load(vork_scene::v2::DEFAULT_PROFILE)?.resolve(+ &serde_json::from_value(serde_json::json!({"denoise":false}))?)?;+ let draw=|limit| -> Result<Vec<[f32;4]>> {+ // Only GI sees this limit: reflection and visibility admission use+ // the actual device limits. Seven-row bands include partial groups+ // and a partial final band; every band retains all sample batches.+ TEST_GI_LIMIT.with(|cap|cap.set(limit));+ TEST_GI_BYTES.with(|bytes|bytes.set(0));+ struct Reset;+ impl Drop for Reset {fn drop(&mut self) {TEST_GI_LIMIT.with(|cap|cap.set(None));}}+ let _reset=Reset;+ let mut installed=r.install_with_options(scene.clone(),Path::new("."),InstallOptions {+ variants:crate::pipelines::VariantCompile::Inline,..Default::default()})?;+ assert!(installed.plan.effects.ray_indirect);+ let mut slot=installed.create_frame_slot(&r,ReadbackPrecision::Float)?;+ let image=installed.render_frame(&r,&mut slot,0.)?;+ if let Some(limit)=limit {+ TEST_GI_BYTES.with(|bytes|assert!(bytes.get()>0 && bytes.get()<=limit,+ "GI allocation {} exceeds independent limit {limit}",bytes.get()));+ }+ image.linear_rgba.context("float readback")+ };+ let whole=draw(None)?;+ let banded=draw(Some(33*7*constants::GI_QUERY_BYTES))?;+ assert!(whole.iter().any(|p|p[0]>0.01 && p[1]>0.01));+ assert_eq!(whole,banded,"GI partition changed scene-linear pixels");+ Ok(())+ }++ #[test]+ fn gi_accumulation_bands_follow_both_device_limits() -> Result<()> {+ let mut limits=wgpu::Limits::default();+ for (binding, allocation) in [(128<<20, 1<<30), (1<<30,128<<20), (1<<30,1<<30)] {+ limits.max_storage_buffer_binding_size=binding;+ limits.max_buffer_size=allocation;+ let (rows,bytes)=accumulation_band(&limits,1920,1080)?;+ assert_eq!(bytes,u64::from(rows)*1920*constants::GI_QUERY_BYTES);+ assert!(bytes<=binding.min(allocation));+ assert_eq!(rows,(binding.min(allocation)/(1920*constants::GI_QUERY_BYTES)).min(1080) as u32);+ // Every full-resolution GI cell is processed exactly once, including the tail.+ assert_eq!((0..1080u32.div_ceil(rows)).map(|b|(1080-b*rows).min(rows)).sum::<u32>(),1080);+ }+ limits.max_buffer_size=1920*constants::GI_QUERY_BYTES-1;+ assert!(accumulation_band(&limits,1920,1080).unwrap_err().to_string().contains("GI prepared queries"));+ Ok(())+ }+}diff --git a/crates/vork-render/src/passes/decoupled.rs b/crates/vork-render/src/passes/decoupled.rsindex 7e5d94b..914a387 100644--- a/crates/vork-render/src/passes/decoupled.rs+++ b/crates/vork-render/src/passes/decoupled.rs@@ -1028,7 +1028,7 @@ impl View {for band in 0..bands {let first=(band*installed.materials) as usize*config_stride as usize;let template:CameraConfig=bytemuck::pod_read_unaligned(&configs[first..first+config_size]);- let ray_batch=if s.pipelines.resolve_native.is_some() {vork_slang::registry::MEDIUM_GI_RAY_BATCH} else {32};+ let ray_batch=if s.pipelines.resolve_native.is_some() {vork_slang::registry::GI_RAY_BATCH} else {32};for word in 0..samples.div_ceil(ray_batch) {let mut blocks=Vec::new();for (sampled,capacity,size) in [(false,centroid_capacity,vork_slang::registry::CAMERA_INDIRECT_BLOCK),(true,sampled_capacity,sampled_block)] {@@ -1729,6 +1729,7 @@ mod tests {#[cfg(all(test, vork_private_tests))]include!("decoupled_dielectric_occupancy_bands_preserve_mixed_glass_scene_private.rs");/// Per-sample program and blended shading at 96x64, 8 samples.+ #[cfg(vork_private_tests)]fn program_transparency() -> Result<(Scene,std::path::PathBuf)> {let root=std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples");let mut scene=crate::load_test_fixture(&root.join("program-transparency.json"), include_str!("../../tests/presets/program-transparency-874d5753.json"))?;@@ -1738,6 +1739,7 @@ mod tests {/// Per-sample program and blended shading split into bands reproduces the/// one-band image exactly: each band classifies, evaluates and composes its rows.#[test]+ #[cfg(vork_private_tests)]fn shading_bands_reproduce_the_single_band_image() -> Result<()> {let Some(mut r) = crate::test_renderer()? else {return Ok(());};let (scene,root)=program_transparency()?;@@ -1792,6 +1794,7 @@ mod tests {/// A frame whose evaluations overflow the view's estimate redoes with the/// reported demand, destroys the outgrown storage, and keeps its pixels.#[test]+ #[cfg(vork_private_tests)]fn evaluation_overflow_redoes_and_destroys_the_outgrown_storage() -> Result<()> {let Some(mut r) = crate::test_renderer()? else {return Ok(());};let (scene,root)=program_transparency()?;@@ -1822,6 +1825,7 @@ mod tests {/// Recovery preserves an accepted successor's pixels and GPU-only fence,/// but releases the saved result when a different request uses that slot.#[test]+ #[cfg(vork_private_tests)]fn recovery_retains_an_accepted_queued_exposure() -> Result<()> {let Some(mut r) = crate::test_renderer()? else { return Ok(()); };let (scene, root) = program_transparency()?;@@ -1912,6 +1916,7 @@ mod tests {// Empty SIMD lanes must never reach descriptor loads in either the direct// opaque walk or the grouped one-sample transparent walk.#[test]+ #[cfg(vork_private_tests)]fn single_sample_shading_preserves_sparse_pixel_execution() -> Result<()> {let Some(r) = crate::test_renderer()? else {return Ok(());};let root=std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples");diff --git a/crates/vork-render/src/passes/reflections.rs b/crates/vork-render/src/passes/reflections.rsindex c663d0b..401626b 100644--- a/crates/vork-render/src/passes/reflections.rs+++ b/crates/vork-render/src/passes/reflections.rs@@ -14,6 +14,8 @@ pub(crate) fn record_fields(buffer:&wgpu::Buffer, bytes:u64)->Vec<wgpu::BufferBi/// One retained hit-shading specialization for the complete installed scene.pub(crate) fn pipeline(r: &Renderer, cached: &crate::pipelines::CachedPipelines, features: crate::forward_variant::FeatureMask, probes: bool, mode: &crate::pipelines::VariantCompile) -> Result<wgpu::ComputePipeline> {let kernel=cached.drawn_kernel(crate::pipelines::ProgramKernel::Reflections { features }, mode,&r.compiler);+ #[cfg(test)]+ r.compiler.hit_selections.lock().unwrap().push((crate::pipelines::ProgramKernel::Reflections { features },kernel));let (module, entry) = cached.program_kernel(kernel)?;let layout=crate::rt::reflections_hits_layout(&r.device,&cached.mat_layout,probes,cached.resolve_native.as_ref().map_or(0,|n| if n.visibility_lights>0 {n.sample_pages} else {0}));let pipeline=r.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {diff --git a/crates/vork-render/src/pipelines.rs b/crates/vork-render/src/pipelines.rsindex e11e271..5a8a6ef 100644--- a/crates/vork-render/src/pipelines.rs+++ b/crates/vork-render/src/pipelines.rs@@ -88,6 +88,8 @@ pub(crate) fn base<T>(slot: &OnceLock<T>) -> &T {/// call that started them, so they cannot borrow the Renderer.#[derive(Clone)]pub(crate) struct Compiler {+ #[cfg(test)]+ pub(crate) hit_selections: std::sync::Arc<Mutex<Vec<(ProgramKernel, ProgramKernel)>>>,device: wgpu::Device,cache: Option<wgpu::PipelineCache>,/// Wall time per driver pipeline creation call; concurrent times overlap.@@ -146,6 +148,8 @@ impl Compiler {known: Known,) -> Self {Self {+ #[cfg(test)]+ hit_selections: Default::default(),device: device.clone(),cache: cache.cloned(),timings: Default::default(),@@ -235,6 +239,7 @@ impl Compiler {pub(crate) fn render(&self, descriptor: &wgpu::RenderPipelineDescriptor<'_>) -> wgpu::RenderPipeline {let _permit = self.permit(false);let start = std::time::Instant::now();+ let _progress = vork_slang::progress::Job::start(true);let pipeline = crate::gpu_memory::render_pipeline(&self.device, descriptor);self.created.fetch_add(1, std::sync::atomic::Ordering::AcqRel);self.time(descriptor.label, start);@@ -243,6 +248,7 @@ impl Compiler {pub(crate) fn compute(&self, descriptor: &wgpu::ComputePipelineDescriptor<'_>) -> wgpu::ComputePipeline {let _permit = self.permit(false);let start = std::time::Instant::now();+ let _progress = vork_slang::progress::Job::start(true);let pipeline = crate::gpu_memory::compute_pipeline(&self.device, descriptor);self.created.fetch_add(1, std::sync::atomic::Ordering::AcqRel);self.time(descriptor.label, start);@@ -334,6 +340,9 @@ pub(crate) enum VariantCompile {/// `vork setup`: Fallback's choices, and the hit kernels compile the superset/// key a later Fallback install draws with (CachedPipelines::drawn_kernel).Setup,+ /// Startup's ordinary table configuration: retain material proofs while+ /// sharing hit evaluators across light mixes. Other kernels use Setup.+ SetupPlain,/// Compile every variant before install returns.Inline,/// Tests: background workers start only once the gate opens, regardless of warmth.@@ -347,11 +356,11 @@ impl VariantCompile {match self {Self::Inline=>false,Self::Gated(_)=>true,- Self::Background|Self::Fallback|Self::Setup=>!warm && generic_ready,+ Self::Background|Self::Fallback|Self::Setup|Self::SetupPlain=>!warm && generic_ready,}}/// One-frame choices: draw generics and compile no later variant.- pub(crate) fn fallback(&self)->bool {matches!(self,Self::Fallback|Self::Setup)}+ pub(crate) fn fallback(&self)->bool {matches!(self,Self::Fallback|Self::Setup|Self::SetupPlain)}}/// A retained variant; the caller supplies a pipeline fallback or keeps its existing passes.#[derive(Clone)]@@ -423,6 +432,21 @@ pub(crate) enum ProgramKernel {Decoupled { stage: ShadeStage, features: FeatureMask, subsurface: bool, emitter_profiles: bool, boundaries: u32 },}impl ProgramKernel {+ /// Untextured, unlayered table materials share one hit evaluator across light+ /// mixes. Keep runtime metalness, sidedness and every analytic light kind;+ /// do not turn on unrelated texture/layer/transport capabilities.+ pub(crate) fn plain_hit(self) -> Option<Self> {+ use crate::forward_variant::*;+ let lighting = FEATURE_LIGHT_TYPES | FEATURE_PUNCTUAL | FEATURE_FINITE+ | FEATURE_RECTANGLE | FEATURE_ELLIPSE | FEATURE_SHADOW_RAYS;+ let allowed = lighting | FEATURE_SPECIALIZED | FEATURE_LIT | FEATURE_SIDED+ | FeatureMask::from(SHADING_METAL);+ match self {+ Self::Gi { features } if features & FEATURE_SPECIALIZED != 0 && features & !allowed == 0 => Some(Self::Gi { features: allowed }),+ Self::Reflections { features } if features & FEATURE_SPECIALIZED != 0 && features & !allowed == 0 => Some(Self::Reflections { features: allowed }),+ _ => None,+ }+ }/// The same kernel over the generic feature key (variant.slang Unspecialized:/// layered and metallic shading kept), for kernels that otherwise specialize to/// the scene and have no shipped generic: ray GI, reflection and probe hits,@@ -958,10 +982,18 @@ impl CachedPipelines {/// Shipped late-specialization artifacts exist for every capability key;/// prefer a remembered device superset before consulting artifact presence.pub(crate) fn drawn_kernel(&self, kernel: ProgramKernel, mode: &VariantCompile, compiler: &Compiler) -> ProgramKernel {+ if matches!(mode, VariantCompile::Background | VariantCompile::Fallback)+ && !compiler.is_known(&self.kernel_content_key(kernel))+ {+ if let Some(plain) = kernel.plain_hit().filter(|plain| compiler.is_known(&self.kernel_content_key(*plain))) {+ return plain;+ }+ }let Some(superset) = kernel.superset() else { return kernel };let stored = |kernel| self.shader.kernel_stored(kernel).unwrap_or(false);match mode {VariantCompile::Setup => superset,+ VariantCompile::SetupPlain => kernel.plain_hit().unwrap_or(superset),VariantCompile::Fallback if !compiler.is_known(&self.kernel_content_key(kernel))&& compiler.is_known(&self.kernel_content_key(superset)) => superset,VariantCompile::Fallback if !stored(kernel) && stored(superset) => superset,@@ -1743,6 +1775,23 @@ fn warm_geometry(r:&Renderer, p:&CachedPipelines, keys:Vec<GeometryKey>) -> Resu#[cfg(test)]mod registry_identity_tests {use super::*;++ #[test]+ fn plain_hit_preserves_capabilities_and_rejects_complex_materials() {+ use crate::forward_variant::*;+ for features in [FEATURE_SPECIALIZED, FEATURE_SPECIALIZED | FeatureMask::from(SHADING_METAL)+ | FEATURE_SIDED | FEATURE_LIGHT_TYPES | FEATURE_FINITE | FEATURE_RECTANGLE] {+ let ProgramKernel::Gi { features: plain } = (ProgramKernel::Gi { features }).plain_hit().unwrap() else { unreachable!() };+ assert_eq!(features & !plain, 0, "a plain hit key may only add capabilities");+ assert_eq!(plain & ((1 << (TEXTURE_FEATURES + 2)) - 4), 0, "no texture lookups");+ assert_eq!(plain & FeatureMask::from(SHADING_LAYERS), 0, "no layered material evaluation");+ assert_eq!((ProgramKernel::Reflections { features }).plain_hit(), Some(ProgramKernel::Reflections { features: plain }));+ }+ for features in [0, FEATURE_SPECIALIZED | FEATURE_COAT, FEATURE_SPECIALIZED | FEATURE_TRANSMISSION,+ FEATURE_SPECIALIZED | FEATURE_LOBES, FEATURE_SPECIALIZED | (1 << 2)] {+ assert!((ProgramKernel::Gi { features }).plain_hit().is_none());+ }+ }#[test]fn surface_warm_keys_ignore_display_denoise_and_camera_programs() {let base=crate::slang_forward::SlangScene::default();diff --git a/crates/vork-render/src/programs.rs b/crates/vork-render/src/programs.rsindex ce7c55e..3b49ef3 100644--- a/crates/vork-render/src/programs.rs+++ b/crates/vork-render/src/programs.rs@@ -114,13 +114,6 @@ pub(crate) fn instance(scene: &v2::Scene, name: &str) -> Result<Option<Instance>}))}-/// A cached Slang proof about one program and the files it read.-#[derive(serde::Serialize, serde::Deserialize)]-struct Proof<T> {- value: T,- dependencies: Vec<PathBuf>,-}-pub(crate) struct Programs {/// Program and attribute identity for the installed pipeline cache.pub(crate) identity: String,@@ -316,7 +309,7 @@ pub(crate) fn normalize_launch_bindings(r:&Renderer, scene:&mut v2::Scene, base:for node in nodes {if let v2::NodeKind::Light {shape:v2::LightShape::Environment,material:Some(name),..}=&node.kind {if scene.materials[name].inputs.values().any(|v|matches!(v,v2::Input::Texture(binding) if scene.images[&binding.image].render.is_some())) {- eprintln!("warning: node {:?}: ignored environment material {name} sampling a render image; using the light's colour",node.name);+ crate::warnings::dropped("environment_render_image", serde_json::json!({"node":node,"material":scene.materials[name]}), format!("warning: node {:?}: ignored environment material {name} sampling a render image; using the light's colour",node.name));if let v2::NodeKind::Light {material,..}=&mut node.kind {*material=None;}}}@@ -331,7 +324,7 @@ pub(crate) fn normalize_launch_bindings(r:&Renderer, scene:&mut v2::Scene, base:if material.program=="std/openpbr" {if implicit && (material.inputs.get("subsurface_weight").is_some_and(|v|!matches!(v,v2::Input::Number(x) if *x==0.)) || scene.animation.iter().flat_map(|l|l.tracks.iter().flatten()).any(|t|t.path==["materials",binding.as_str(),"inputs","subsurface_weight"])) {let mut m=material.clone();m.inputs.insert("subsurface_weight".into(),v2::Input::Number(0.));- eprintln!("warning: node {:?}, material {}: ignored subsurface scattering on implicit geometry",node.name,binding);+ crate::warnings::dropped("implicit_subsurface", serde_json::json!({"node":node.name,"material":binding,"inputs":material.inputs,"tracks":scene.animation.iter().flat_map(|layer|layer.tracks.iter().flatten()).filter(|track|matches!(track.path.as_slice(),[root,target,..] if root=="materials" && target.as_str()==binding.as_str())).collect::<Vec<_>>()}), format!("warning: node {:?}, material {}: ignored subsurface scattering on implicit geometry",node.name,binding));replacement=Some(m);}} else if !curves || implicit || computed {@@ -345,7 +338,7 @@ pub(crate) fn normalize_launch_bindings(r:&Renderer, scene:&mut v2::Scene, base:};if curves && computed && capability.physical_hair {*path_needed=true;}if (capability.hair && !curves) || (implicit && capability.subsurface) {- eprintln!("warning: node {:?}, material {}: ignored unsupported {} surface on this geometry; using default OpenPBR surface",node.name,binding,if capability.hair {"Hair"} else {"custom subsurface"});+ crate::warnings::dropped("surface_geometry", serde_json::json!({"node":node.name,"material":binding,"inputs":material.inputs,"program":material.program,"tracks":scene.animation.iter().flat_map(|layer|layer.tracks.iter().flatten()).filter(|track|matches!(track.path.as_slice(),[root,target,..] if root=="materials" && target.as_str()==binding.as_str())).collect::<Vec<_>>()}), format!("warning: node {:?}, material {}: ignored unsupported {} surface on this geometry; using default OpenPBR surface",node.name,binding,if capability.hair {"Hair"} else {"custom subsurface"}));replacement=Some(serde_json::from_value(serde_json::json!({}))?);}}@@ -415,20 +408,21 @@ pub(crate) fn mesh_stages(r: &Renderer, scene: &v2::Scene, base: &Path) -> Resullet mut groups=std::collections::BTreeMap::<(String,PathBuf),Vec<String>>::new();for (program,_) in programs {let (source,origin)=material_source(scene,base,program)?;- groups.entry((source,origin.with_file_name("material.slang"))).or_default().push(program.to_owned());+ groups.entry((source,origin.to_path_buf())).or_default().push(program.to_owned());}let programs:Vec<_>=groups.into_iter().collect();let probe=|((source,origin),names):&((String,PathBuf),Vec<String>)| -> Result<Vec<(String,Stages)>> {- let stages=cached(r, program_key(b"mesh-stages-v4", &abi, source, origin)?.finalize(), |p: &Proof<Stages>| &p.dependencies, || {- let (declarations, dependencies) = compiler.stages(&abi, source, origin)?;+ let identity=program_identity(&r.disk_cache,&compiler,&abi,source,origin)?;+ let stages=cached(r, input_key(b"mesh-stages-v5", &abi, &identity.identity)?.finalize(), &compiler.with_identity(&identity), &abi, source, origin, |compiler| {+ let (declarations, _) = compiler.stages(&abi, source, origin)?;let stages = Stages {surface: declarations.contains("surface"),medium: declarations.contains("medium"),displacement: declarations.contains("displace"),};- ensure!(stages.surface || stages.medium, "program {}: mesh program must export surface or medium",names[0]);- Ok(Proof { value: stages, dependencies })- })?.value;+ ensure!(stages.surface || stages.medium, "program {}: mesh program must export surface or medium; lit() and displace() supplement surface(), they do not replace it; see vork help programs --all",names[0]);+ Ok(stages)+ })?;Ok(names.iter().map(|name|(name.clone(),stages)).collect())};parallel_map(&programs, probe)?.into_iter().flatten().collect::<std::collections::BTreeMap<_,_>>()@@ -488,7 +482,20 @@ pub(crate) fn install<'a>(return Ok(None);}let compiler = Compiler::discover();- let mut compiled: Vec<Program> = parallel_map(&sources, |(source, origin)| compile(r, &compiler, &abi, source, origin))?;+ let compiled: Vec<Program> = parallel_map(&sources, |(source, origin)| compile(r, &compiler, &abi, source, origin))?;+ // Raw grouping above only avoids duplicate work. Program routing must use+ // compiler identity too: commenting one of two identical aliases must not+ // create another program bin or grow the scene dispatcher.+ let identities=compiled.iter().map(|p|p.install_identity.as_ref().map(|i|i.identity.as_slice()).context("material input identity")).collect::<Result<Vec<_>>>()?;+ let remap=semantic_indices(identities.into_iter());+ let mut unique=Vec::new();+ let mut unique_sources=Vec::new();+ for (index,(program,source)) in compiled.into_iter().zip(sources).enumerate() {+ if remap[index]==unique.len() {unique.push(program);unique_sources.push(source);}+ }+ for index in ids.values_mut() {*index=remap[*index];}+ let mut compiled=unique;+ let sources=unique_sources;for (program,(_,origin)) in compiled.iter().zip(&sources) {if !program.warnings.trim().is_empty() {eprintln!("{}: {}",origin.display(),program.warnings.trim());}}@@ -571,28 +578,37 @@ pub(crate) fn install<'a>(}))}-/// One cached compile. The key covers everything the output depends on except-/// imported files, which are recorded in the entry and revalidated here.-fn compile(+/// One cached compile. The key includes compiler tokens and resolved imports;+/// proof subprocesses verify their captured imports before publication.+pub(crate) fn compile(r: &Renderer,compiler: &Compiler,abi: &Abi,source: &str,origin: &Path,) -> Result<Program> {- let key = program_key(b"program-v2", abi, source, origin)?.finalize();- let program = cached(+ let authored_origin=origin;+ let identity=program_identity(&r.disk_cache,compiler,abi,source,&origin)?;+ let key = input_key(b"program-v4", abi, &identity.identity)?.finalize();+ let mut program = cached(r,key,- |p: &Program| &p.dependencies,- || {+ &compiler.with_identity(&identity),+ abi, source, &origin,+ |compiler| {let tag = &key.to_hex()[..12];let program = compiler- .compile_surface(abi, source, &origin.with_file_name("material.slang"), tag)+ .compile_surface(abi, source, &origin, tag).with_context(|| format!("compile {}", origin.display()))?;Ok(program)},)?;+ program.set_native_source(source, origin)?;+ program.install_identity=Some(identity);+ for stage in &program.dropped_stages {+ crate::warnings::dropped("hair_stage", serde_json::json!({"program":authored_origin,"stage":stage}),+ format!("{stage} stage on Hair; retaining the physical hair surface"));+ }Ok(program)}@@ -636,7 +652,7 @@ fn validate_bound_geometry(if let Some(&i) = ids.get(&instance_key(&instance)) {for image in &instance.images {if compiled[i].capabilities.displacement && compiled[i].displacement_images.contains(&image.input) && image.source.changes_between_frames() {- eprintln!("warning: material {name}: ignored displacement sampling a changing/render image before geometry evaluation");+ crate::warnings::dropped("displacement_image", serde_json::json!({"material":name,"program":scene.materials[name].program,"image":image.input,"inputs":scene.materials[name].inputs}), format!("warning: material {name}: ignored displacement sampling a changing/render image before geometry evaluation"));compiled[i].capabilities.displacement=false;}}@@ -668,10 +684,12 @@ fn validate_bound_geometry(/// Map `f` over `items` on up to one thread per core, keeping their order.fn parallel_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Result<R> + Sync) -> Result<Vec<R>> {+ let warning_collector = crate::warnings::Collector::current();let cursor = std::sync::atomic::AtomicUsize::new(0);std::thread::scope(|scope| {let workers = items.len().min(std::thread::available_parallelism().map_or(1, usize::from));let jobs: Vec<_> = (0..workers).map(|_| scope.spawn(|| {+ let _warning_scope = warning_collector.as_ref().map(|c| c.enter());let mut results = Vec::new();loop {let index = cursor.fetch_add(1, std::sync::atomic::Ordering::Relaxed);@@ -687,46 +705,156 @@ fn parallel_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Result<R> + Syn})}-/// The cache key prefix of a proof about one program source.-fn program_key(tag: &[u8], abi: &Abi, source: &str, origin: &Path) -> Result<blake3::Hasher> {+fn semantic_indices<'a>(identities:impl Iterator<Item=&'a [u8]>)->Vec<usize> {+ let mut unique=std::collections::BTreeMap::new();+ identities.map(|identity| {+ let next=unique.len();+ *unique.entry(identity).or_insert(next)+ }).collect()+}++/// The cache key prefix of a proof about one compiler-input snapshot.+fn input_key(tag: &[u8], abi: &Abi, identity: &[u8]) -> Result<blake3::Hasher> {let mut key = blake3::Hasher::new();- key.update(tag);- key.update(abi.cache_identity()?.as_bytes());- key.update(origin.parent().unwrap_or(Path::new(".")).to_string_lossy().as_bytes());- key.update(source.as_bytes());+ let abi_identity=abi.cache_identity()?;+ for part in [tag,abi_identity.as_bytes(),identity] {+ key.update(&(part.len() as u64).to_le_bytes());key.update(part);+ }Ok(key)}+fn program_identity(store: &disk_cache::Store, compiler: &Compiler, abi: &Abi, source: &str, origin: &Path) -> Result<vork_slang::InputIdentity> {+ bound_program_identity(store,compiler,abi,source,origin,"")+}++pub(crate) fn bound_program_identity(+ store: &disk_cache::Store, compiler: &Compiler, abi: &Abi,+ source: &str, origin: &Path, bindings: &str,+) -> Result<vork_slang::InputIdentity> {+ let mut raw=input_key(b"program-input-receipt-v2",abi,source.as_bytes())?;+ raw.update(&(bindings.len() as u64).to_le_bytes());raw.update(bindings.as_bytes());+ for part in [compiler.input_policy(),std::env::current_dir()?.join(origin).to_string_lossy().into_owned()] {+ raw.update(&(part.len() as u64).to_le_bytes());raw.update(part.as_bytes());+ }+ let path=store.path("slang-input",1,raw.finalize());+ if let Some(bytes)=disk_cache::read(&path)+ && let Ok(identity)=serde_json::from_slice::<vork_slang::InputIdentity>(&bytes)+ && identity.valid() { return Ok(identity); }+ let prepared=compiler.prepare_bound_program(abi,source,origin,bindings)?;+ let identity=prepared.receipt();+ let _=disk_cache::write(&path,&serde_json::to_vec(&identity)?);+ Ok(identity)+}++/// Exact-input receipts and normalized identities use the same native artifact+/// store. A miss retains the captured filesystem for subsequent code generation.+pub(crate) fn native_input_identity(+ cache: &dyn Fn(blake3::Hash)->PathBuf, compiler: &Compiler,+ modules: &[(&str,&str)], main: &str, entries: &[(&str,&str)], args: &[&str],+ identities: &std::collections::BTreeMap<String,Vec<u8>>,+) -> Result<(vork_slang::InputIdentity,Option<vork_slang::PreparedModules>)> {+ let path=native_input_receipt_path(cache,compiler,modules,main,entries,args,identities)?;+ if let Some(identity)=read_native_input_receipt(&path) {return Ok((identity,None));}+ let prepared=compiler.prepare_identified_modules(modules,main,entries,args,identities)?;+ let identity=prepared.receipt();+ let _=disk_cache::write(&path,&serde_json::to_vec(&identity)?);+ Ok((identity,Some(prepared)))+}++/// Scheduling probes must never invoke Slang: an unknown receipt is a miss.+/// Only the build owns preparation, retaining its snapshot through codegen.+pub(crate) fn cached_native_input_identity(+ cache: &dyn Fn(blake3::Hash)->PathBuf, compiler: &Compiler,+ modules: &[(&str,&str)], main: &str, entries: &[(&str,&str)], args: &[&str],+ identities: &std::collections::BTreeMap<String,Vec<u8>>,+) -> Result<Option<vork_slang::InputIdentity>> {+ Ok(read_native_input_receipt(&native_input_receipt_path(cache,compiler,modules,main,entries,args,identities)?))+}++fn read_native_input_receipt(path: &Path) -> Option<vork_slang::InputIdentity> {+ let identity: vork_slang::InputIdentity=serde_json::from_slice(&disk_cache::read(path)?).ok()?;+ identity.valid().then_some(identity)+}++fn native_input_receipt_path(+ cache: &dyn Fn(blake3::Hash)->PathBuf, compiler: &Compiler,+ modules: &[(&str,&str)], main: &str, entries: &[(&str,&str)], args: &[&str],+ identities: &std::collections::BTreeMap<String,Vec<u8>>,+) -> Result<PathBuf> {+ let mut raw=blake3::Hasher::new();+ for part in std::iter::once("native-input-receipt-v1").chain(std::iter::once(main))+ .chain(entries.iter().flat_map(|(entry,stage)|[*entry,*stage])).chain(args.iter().copied())+ .chain(modules.iter().flat_map(|(name,source)|[*name,*source])) {+ raw.update(&(part.len() as u64).to_le_bytes());raw.update(part.as_bytes());+ }+ raw.update(compiler.input_policy().as_bytes());+ for (name,identity) in identities {raw.update(&(name.len() as u64).to_le_bytes());raw.update(name.as_bytes());raw.update(&(identity.len() as u64).to_le_bytes());raw.update(identity);}+ // Exact resolver receipts contain host paths. Keep them in the same store+ // but outside the four portable shader entry kinds shipped with releases.+ let artifact_path=cache(raw.finalize());+ let name=artifact_path.file_name().and_then(|n|n.to_str()).and_then(|n|n.split_once('.')).context("native cache file name")?.0;+ let path=artifact_path.with_file_name(format!("{name}.slang-input-v1.entry"));+ Ok(path)+}++#[cfg(test)]+fn program_key(tag: &[u8], abi: &Abi, source: &str, origin: &Path) -> Result<blake3::Hasher> {+ let prepared=Compiler::discover().prepare_program(abi,source,&origin.to_path_buf())?;+ input_key(tag,abi,prepared.identity())+}+pub(crate) fn cached<T: serde::Serialize + serde::de::DeserializeOwned>(r: &Renderer,key: blake3::Hash,- dependencies: impl Fn(&T) -> &[PathBuf],- build: impl FnOnce() -> Result<T>,+ compiler: &Compiler,+ abi: &Abi, source: &str, origin: &Path,+ build: impl FnOnce(&Compiler) -> Result<T>,) -> Result<T> {- let path = r.disk_cache.path("slang-program", 1, key);- let fingerprint = |files: &[PathBuf]| -> Vec<String> {- files- .iter()- .map(|f| {- std::fs::read(f).map_or_else(- |_| "missing".into(),- |b| blake3::hash(&b).to_hex().to_string(),- )- })- .collect()+ cached_proof(&r.disk_cache,key,compiler,abi,source,origin,|compiler| {+ let start=std::time::Instant::now();+ let result=build(compiler);+ crate::timing::creation(&r.device,&format!("program {key}"),"Slang",start.elapsed().as_secs_f64()*1000.,0.);+ result+ })+}++/// All proof stages share exact compiler receipts. Stage ABI, generated bindings+/// and options belong in the caller key; the compiler policy belongs here.+fn cached_proof<T: serde::Serialize + serde::de::DeserializeOwned>(+ store: &disk_cache::Store, key: blake3::Hash, compiler: &Compiler,+ abi: &Abi, source: &str, origin: &Path,+ build: impl FnOnce(&Compiler) -> Result<T>,+) -> Result<T> {+ let identity=match compiler.input_identity() {+ Some(identity)=>identity.clone(),+ None=>program_identity(store,compiler,abi,source,origin)?,};- if let Some(bytes) = disk_cache::read(&path)- && let Ok((program, deps)) = serde_json::from_slice::<(T, Vec<String>)>(&bytes)- && fingerprint(dependencies(&program)) == deps- {- return Ok(program);+ let key=input_key(key.as_bytes(),abi,&identity.identity)?.finalize();+ let path=store.path("slang-program",2,key);+ if identity.valid()+ && let Some(bytes)=disk_cache::read(&path)+ && let Ok(program)=serde_json::from_slice::<T>(&bytes) {return Ok(program);}+ let (program,receipt)=compiler.with_identity(&identity).capture_inputs(build)?;+ receipt.verify_proof(&identity)?;+ if identity.valid() && receipt.valid() {+ let _=disk_cache::write(&path,&serde_json::to_vec(&program)?);}+ Ok(program)+}++/// Complete generated shaders have no authored resolver inputs. Their caller+/// keys include the whole validated source, binding map and compiler options.+pub(crate) fn cached_generated<T: serde::Serialize + serde::de::DeserializeOwned>(+ r: &Renderer, key: blake3::Hash, build: impl FnOnce() -> Result<T>,+) -> Result<T> {+ let path=r.disk_cache.path("slang-program",2,key);+ if let Some(bytes)=disk_cache::read(&path)+ && let Ok(program)=serde_json::from_slice::<T>(&bytes) {return Ok(program);}let start=std::time::Instant::now();- let program = build();+ let program=build();crate::timing::creation(&r.device,&format!("program {key}"),"Slang",start.elapsed().as_secs_f64()*1000.,0.);let program=program?;- let deps = fingerprint(dependencies(&program));- let _ = disk_cache::write(&path, &serde_json::to_vec(&(&program, deps))?);+ let _=disk_cache::write(&path,&serde_json::to_vec(&program)?);Ok(program)}@@ -749,6 +877,8 @@ pub(crate) struct Native {pub(crate) modules: Vec<(String, String)>,/// Directories program imports resolve from.pub(crate) include: Vec<PathBuf>,+ pub(crate) inputs: Vec<vork_slang::InputIdentity>,+ pub(crate) identities: std::collections::BTreeMap<String,Vec<u8>>,/// The variant module's imports and `struct Programs`.pub(crate) code: String,/// A primary evaluator's program source, for diagnostics.@@ -775,6 +905,8 @@ fn native(abi: &Abi, programs: &[Program], physical_hair: bool, coverage_only: bmodules.push(("vork_constants".into(), format!("#ifndef VORK_AOV_COUNT\n#define VORK_AOV_COUNT {aov_count}\n#endif\n{constants}")));if programs.iter().any(|p| p.capabilities.hair) { modules.push(("hair_lighting".into(), include_str!("../shaders/programs/hair_lighting.slang").into())); }let mut include = Vec::new();+ let mut inputs:Vec<vork_slang::InputIdentity>=Vec::new();+ let mut identities=std::collections::BTreeMap::new();let mut imports = String::new();let mut cases = String::new();let mut aov_cases=String::new();@@ -784,18 +916,22 @@ fn native(abi: &Abi, programs: &[Program], physical_hair: bool, coverage_only: blet mut displacement_cases = String::new();for (i, p) in programs.iter().enumerate() {if !retained(p) {continue;}+ if let Some(identity)=&p.install_identity {+ for previous in &inputs { identity.verify(previous)?; }+ inputs.push(identity.clone());+ }let tag = p.surface.strip_prefix("vork_surface_").and_then(|s| s.split("_0_").next()).context("program surface name")?;- // Imported files are not module text: their content keys the variant cache.- let mut text = p.slang.clone();- for dependency in &p.dependencies {- let bytes = std::fs::read(dependency).unwrap_or_default();- writeln!(text, "// {}: {}", dependency.display(), blake3::hash(&bytes))?;+ // The native entry's compiler snapshot owns resolved import identity.+ modules.push((format!("program_{tag}"), p.slang.clone()));+ if let Some(input)=&p.install_identity {+ if let Some(previous)=identities.insert(format!("program_{tag}"),input.identity.clone()) {+ ensure!(previous==input.identity,"material module identifier collision");+ }}- modules.push((format!("program_{tag}"), text));include.extend(p.include.iter().cloned());writeln!(imports, "import program_{tag};")?;if p.capabilities.hair { writeln!(hair_cases, " case {}u: vork_surface_{tag}(a,base,r); return true;", i+1)?; } else if p.capabilities.lobes {@@ -937,7 +1073,7 @@ fn native(abi: &Abi, programs: &[Program], physical_hair: bool, coverage_only: bif lit { "import lit_dispatch;\n" } else { "" },abi.unpack_closure_slang("o.closure") + CLAMPS);- Ok(Native { camera:Vec::new(), receivers:None, coverage, modules, include, code, name:String::new() })+ Ok(Native { camera:Vec::new(), receivers:None, coverage, modules, include, inputs, identities, code, name:String::new() })}#[cfg(test)]@@ -979,6 +1115,7 @@ mod help_tests {/// falls. Before the ABI exposed it, install failed with/// "'geometry_coat_normal' is not a member of 'Closure'".#[test]+ #[cfg(vork_private_tests)]fn programs_shade_their_coat_normal() -> Result<()> {let Some(r)=crate::test_renderer()? else {return Ok(());};let render=|integrator:&str,coat_normal:&str|->Result<[f32;3]> {@@ -1254,6 +1391,196 @@ impl InputAnimation {#[cfg(test)]mod bundled_origin_tests {use super::*;+ #[test]+ fn program_diagnostics_keep_authored_filename_and_line() {+ let error = program_key(b"diagnostic", &abi(),+ "struct Inputs {};\nClosure surface(ShadingContext c, Inputs i) {return missing_author_symbol;}\n",+ Path::new("author-palette.slang")).err().expect("invalid program");+ let message = format!("{error:#}");+ assert!(message.contains("author-palette.slang:2:"), "{message}");+ assert!(!message.contains("material.slang"), "{message}");+ }++ #[test]+ fn display_proof_cache_tracks_shadowing_and_real_edits() -> Result<()> {+ let root=std::env::temp_dir().join(format!("vork-display-proof-{}",std::process::id()));+ let _=std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(root.join("sub"))?;+ let store=disk_cache::Store::for_test(root.join("cache"));+ let compiler=Compiler::discover(); let abi=abi();+ let origin=root.join("main.slang");+ let source="import sub.wrapper; struct Inputs {}; float3 display(DisplayContext ctx, Inputs inputs){return float3(wrapped());}";+ let helper=root.join("helper.slang"); let sibling=root.join("sub/helper.slang");+ std::fs::write(root.join("sub/wrapper.slang"),"import helper; public float wrapped(){return value();}")?;+ std::fs::write(&helper,"public float value(){return 0.25;}")?;+ // Keep the raw source/options key identical through all dependency edits.+ let key=blake3::hash(b"display-proof-test");+ let build=|compiler:&Compiler|compiler.compile_display(&abi,source,&origin,"cachetest");+ let first=cached_proof(&store,key,&compiler,&abi,source,&origin,build)?;+ let hit:vork_slang::DisplayProgram=cached_proof(&store,key,&compiler,&abi,source,&origin,|_|anyhow::bail!("unchanged inputs recompiled"))?;+ assert_eq!(hit.wgsl,first.wgsl);+ std::fs::write(&sibling,"public float value(){return 0.75;}")?;+ let shadowed=cached_proof(&store,key,&compiler,&abi,source,&origin,build)?;+ assert_ne!(first.wgsl,shadowed.wgsl,"a new preferred import must never reuse stale WGSL");+ std::fs::write(&sibling,"public float value(){return 0.5;}")?;+ let edited=cached_proof(&store,key,&compiler,&abi,source,&origin,build)?;+ assert_ne!(shadowed.wgsl,edited.wgsl,"real edits must never reuse stale WGSL");+ std::fs::remove_file(&sibling)?;+ let restored=cached_proof(&store,key,&compiler,&abi,source,&origin,build)?;+ assert_eq!(restored.wgsl,first.wgsl);+ std::fs::remove_dir_all(root)?;+ Ok(())+ }++ #[test]+ fn display_proof_cache_rejects_publication_races() -> Result<()> {+ let root=std::env::temp_dir().join(format!("vork-display-race-{}",std::process::id()));+ let _=std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root)?;+ let store=disk_cache::Store::for_test(root.join("cache"));+ let compiler=Compiler::discover(); let abi=abi();+ let origin=root.join("main.slang"); let sibling=root.join("helper.slang");+ let source="import helper; struct Inputs {}; float3 display(DisplayContext ctx, Inputs inputs){return float3(value());}";+ std::fs::write(&sibling,"public float value(){return 0.5;}")?;+ let build=|compiler:&Compiler|compiler.compile_display(&abi,source,&origin,"cachetest");+ let race_key=blake3::hash(b"display-publication-race");+ let raced:Result<vork_slang::DisplayProgram>=cached_proof(&store,race_key,&compiler,&abi,source,&origin,|compiler| {+ let program=build(compiler)?;+ // Deterministically edit after compiler reads but before publication.+ std::fs::write(&sibling,"public float value(){return 0.875;}")?;+ Ok(program)+ });+ assert!(raced.is_err(),"old output must not be associated with new bytes");+ let mut rebuilt=false;+ let fresh=cached_proof(&store,race_key,&compiler,&abi,source,&origin,|compiler| {rebuilt=true;build(compiler)})?;+ assert!(rebuilt,"a raced compilation must not publish a cache entry");+ assert!(fresh.wgsl.contains("0.875"));+ std::fs::remove_dir_all(root)?;+ Ok(())+ }++ #[test]+ fn display_proof_cache_rejects_unidentified_imports() -> Result<()> {+ let root=std::env::temp_dir().join(format!("vork-proof-extra-inputs-{}",std::process::id()));+ std::fs::create_dir_all(&root)?;+ std::fs::write(root.join("helper.slang"),"public float value(){return 0.75;}")?;+ let store=disk_cache::Store::for_test(root.join("cache"));+ let compiler=Compiler::discover(); let abi=abi(); let origin=root.join("main.slang");+ let source="struct Inputs {}; float3 display(DisplayContext ctx, Inputs i){return float3(0.25);}";+ let actual="import helper; struct Inputs {}; float3 display(DisplayContext ctx, Inputs i){return float3(value());}";+ let key=blake3::hash(b"proof-extra-inputs");+ let result=cached_proof(&store,key,&compiler,&abi,source,&origin,|compiler|+ compiler.compile_display(&abi,actual,&origin,"extra"));+ assert!(result.is_err(),"a wrapper-only dependency must not escape the proof key");+ let mut rebuilt=false;+ let fresh=cached_proof(&store,key,&compiler,&abi,source,&origin,|compiler| {+ rebuilt=true;compiler.compile_display(&abi,source,&origin,"extra")+ })?;+ assert!(rebuilt,"an incomplete identity must not publish an artifact");+ assert!(fresh.wgsl.contains("0.25"));+ std::fs::remove_dir_all(root)?;+ Ok(())+ }++ #[test]+ fn embedded_proof_cache_remains_portable_across_origins() -> Result<()> {+ let root=std::env::temp_dir().join(format!("vork-portable-proof-{}",std::process::id()));+ let store=disk_cache::Store::for_test(root.clone());+ let key=blake3::hash(b"portable-display-proof");+ let source="struct Inputs {}; float3 display(DisplayContext ctx, Inputs inputs){return ctx.color;}";+ let abi=abi(); let compiler=Compiler::discover();+ let first_origin=root.join("setup/embedded.slang");+ let other_origin=root.join("scene/embedded.slang");+ std::fs::create_dir_all(first_origin.parent().unwrap())?;+ std::fs::create_dir_all(other_origin.parent().unwrap())?;+ let first=cached_proof(&store,key,&compiler,&abi,source,&first_origin,|compiler|+ compiler.compile_display(&abi,source,&first_origin,"portable"))?;+ let hit:vork_slang::DisplayProgram=cached_proof(&store,key,&compiler,&abi,source,&other_origin,+ |_|anyhow::bail!("embedded proof lost portability"))?;+ assert_eq!(first.wgsl,hit.wgsl);+ std::fs::remove_dir_all(root)?;+ Ok(())+ }++ #[test]+ fn all_authored_stages_use_checked_cache_boundary() -> Result<()> {+ let root=std::env::temp_dir().join(format!("vork-stage-smoke-{}",std::process::id()));+ std::fs::create_dir_all(&root)?;+ let store=disk_cache::Store::for_test(root.join("cache"));+ let compiler=Compiler::discover();let abi=abi();+ macro_rules! stage {($name:literal,$source:expr,$method:ident)=>{{+ let source=$source;let origin=root.join(concat!($name,".slang"));+ let key=blake3::hash($name.as_bytes());+ let _:serde_json::Value=cached_proof(&store,key,&compiler,&abi,source,&origin,|compiler|+ Ok(serde_json::to_value(compiler.$method(&abi,source,&origin,"stagesmoke")?)?))?;+ let _:serde_json::Value=cached_proof(&store,key,&compiler,&abi,source,&origin,+ |_|anyhow::bail!("unchanged {} stage recompiled",$name))?;+ }}}+ stage!("surface","struct Inputs {}; Closure surface(ShadingContext c,Inputs i){Closure o={};o.base_color=float3(0.3);return o;}",compile_surface);+ stage!("camera",vork_slang::module_source("std/camera").unwrap(),compile_camera);+ stage!("environment","struct Inputs {}; float3 environment(EnvironmentContext c,Inputs i){return float3(c.direction.y);}",compile_environment);+ stage!("medium",vork_slang::module_source("std/fog").unwrap(),compile_medium);+ stage!("composite","struct Inputs {float gain=1.;}; float4 composite(CompositeContext c,Inputs i){return compositor_sample(c.uv)*i.gain;}",compile_composite);+ stage!("propagation","struct Inputs {}; PropagationStep propagation(PropagationContext c,Inputs i){PropagationStep s;s.direction=c.direction;s.distance=1.;return s;}",compile_propagation);+ let source="struct Inputs {uint amount=3;}; void compute(ComputeContext c,Inputs i){result_store(c.id.x,i.amount);}";+ let bindings="struct Tick {uint frame;float time;float dt;uint reserved;}; [[vk::binding(0,0)]] ConstantBuffer<Tick> vork_tick; struct Offset {uint4 value;}; [[vk::binding(1,0)]] ConstantBuffer<Offset> vork_offset; [[vk::binding(2,0)]] RWStructuredBuffer<uint> result; void result_store(uint i,uint v){result[i]=v;}";+ let origin=root.join("compute.slang");let key=blake3::hash(b"compute");+ let inputs=bound_program_identity(&store,&compiler,&abi,source,&origin,bindings)?;+ let compiler=compiler.with_identity(&inputs);+ let _:vork_slang::ComputeProgram=cached_proof(&store,key,&compiler,&abi,source,&origin,|compiler|+ compiler.compile_compute(source,&origin,bindings,64,[1,1,1]))?;+ let _:vork_slang::ComputeProgram=cached_proof(&store,key,&compiler,&abi,source,&origin,+ |_|anyhow::bail!("unchanged compute stage recompiled"))?;+ assert!(compiler.prepare_bound_program(&abi,"struct Inputs {}; uint bad=vork_tick.frame;",&origin,bindings).is_err(),"generated bindings must not relax authored reserved-name checks");+ std::fs::remove_dir_all(root)?;Ok(())+ }++ #[test]+ fn semantic_program_aliases_keep_ids_when_only_comments_change() -> Result<()> {+ let compiler=Compiler::discover(); let abi=abi(); let origin=Path::new("material.slang");+ let source="struct Inputs {}; Closure surface(ShadingContext ctx,Inputs i){Closure c={};c.base_color=float3(0.25);return c;}";+ let base=compiler.prepare_program(&abi,source,origin)?;+ let comment=compiler.prepare_program(&abi,&format!("// alias description\n{source}"),origin)?;+ let edited=compiler.prepare_program(&abi,&source.replace("0.25","0.75"),origin)?;+ assert_eq!(semantic_indices([base.identity(),comment.identity(),edited.identity(),base.identity()].into_iter()),vec![0,0,1,0]);+ Ok(())+ }++ #[test]+ fn native_store_reuses_comments_and_rebuilds_imported_values() -> Result<()> {+ let root=std::env::temp_dir().join(format!("vork-program-identity-store-{}",std::process::id()));+ std::fs::create_dir_all(&root)?;+ let store=disk_cache::Store::for_test(root.join("cache"));+ let cache=|key|store.path("slang-variant",1,key);+ let helper=root.join("helper.slang");+ std::fs::write(&helper,"public float value(){return 0.25;}")?;+ let main="import helper; RWStructuredBuffer<float> result; [numthreads(1,1,1)] void main(uint3 id:SV_DispatchThreadID){result[id.x]=value();}";+ let compiler=Compiler::discover();+ let include=root.display().to_string();+ let args=["-target","spirv","-I",include.as_str()];+ let entries=[("main","compute")];+ let modules=[("main",main)];+ assert!(cached_native_input_identity(&cache,&compiler,&modules,"main",&entries,&args,&Default::default())?.is_none(),"cold scheduling probe must only report a miss");+ let (original,prepared)=native_input_identity(&cache,&compiler,&modules,"main",&entries,&args,&Default::default())?;+ let binary=prepared.context("first input must be captured")?.compile()?;+ let artifact=cache(blake3::hash(&original.identity));+ disk_cache::write(&artifact,&binary)?;+ let (_,prepared)=native_input_identity(&cache,&compiler,&modules,"main",&entries,&args,&Default::default())?;+ ensure!(prepared.is_none(),"exact unchanged input should reuse its receipt");+ assert_eq!(cached_native_input_identity(&cache,&compiler,&modules,"main",&entries,&args,&Default::default())?.unwrap().identity,original.identity);+ std::fs::write(&helper,"// explanatory comment\npublic float value() { return 0.25; }")?;+ assert!(cached_native_input_identity(&cache,&compiler,&modules,"main",&entries,&args,&Default::default())?.is_none(),"changed resolver input must not be reported stored");+ let (comment,prepared)=native_input_identity(&cache,&compiler,&modules,"main",&entries,&args,&Default::default())?;+ ensure!(prepared.is_some(),"changed bytes require compiler revalidation");+ assert_eq!(disk_cache::read(&cache(blake3::hash(&comment.identity))),Some(binary.clone()),"comment must hit the existing artifact");+ std::fs::write(&helper,"public float value(){return 0.75;}")?;+ let (edited,prepared)=native_input_identity(&cache,&compiler,&modules,"main",&entries,&args,&Default::default())?;+ assert!(disk_cache::read(&cache(blake3::hash(&edited.identity))).is_none(),"real imported edit must miss the store");+ assert_ne!(binary,prepared.context("edited input must be captured")?.compile()?);+ std::fs::remove_dir_all(root)?;+ Ok(())+ }+#[test]fn setup_surface_artifacts_are_reused_from_another_scene_directory() -> Result<()> {let Some(r)=crate::test_renderer()? else {return Ok(());};@@ -1262,9 +1589,9 @@ mod bundled_origin_tests {let abi=abi();let first=compile(&r,&Compiler::discover(),&abi,&source,&origin)?;let (source,origin)=material_source(&scene,Path::new("/scenes/shot"),"std/hair")?;- let key=program_key(b"program-v2",&abi,&source,&origin)?.finalize();- let second:Program=cached(&r,key,|p:&Program|&p.dependencies,- ||anyhow::bail!("bundled hair recompiled in another scene directory"))?;+ let key=program_key(b"program-v4",&abi,&source,&origin)?.finalize();+ let second:Program=cached(&r,key,&Compiler::discover(),&abi,&source,&origin,+ |_|anyhow::bail!("bundled hair recompiled in another scene directory"))?;assert_eq!(first.slang,second.slang);assert_eq!(first.wgsl,second.wgsl);Ok(())@@ -1288,3 +1615,7 @@ mod bundled_origin_tests {Ok(())}}++#[cfg(all(test, vork_private_tests))]+#[path = "programs_texture_tests_private.rs"]+mod texture_install_tests;diff --git a/crates/vork-render/src/propagation.rs b/crates/vork-render/src/propagation.rsindex 38d50c5..7567779 100644--- a/crates/vork-render/src/propagation.rs+++ b/crates/vork-render/src/propagation.rs@@ -13,8 +13,9 @@ pub(crate) fn prepare(r:&Renderer,scene:&vork_scene::v2::Scene,base:&Path)->Resulet abi=programs::abi();let mut hash=blake3::Hasher::new();hash.update(b"authored-segments-v1");hash.update(include_str!("../../vork-slang/src/propagation.rs").as_bytes());hash.update(abi.cache_identity()?.as_bytes());hash.update(source.as_bytes());hash.update(origin.to_string_lossy().as_bytes());let key=hash.finalize();let tag=key.to_hex();- let program=programs::cached(r,key,|p:&vork_slang::PropagationProgram|&p.dependencies,- ||vork_slang::Compiler::discover().compile_propagation(&abi,&source,&origin,&tag[..12]))?;+ let program=programs::cached(r,key,&vork_slang::Compiler::discover(),+ &abi, &source, &origin,+ |compiler|compiler.compile_propagation(&abi,&source,&origin,&tag[..12]))?;if !program.warnings.trim().is_empty() {eprintln!("{}",program.warnings);}let words=program.inputs.pack(&std::collections::BTreeMap::new(),|_,_|unreachable!())?;let mut text=program.native.clone();diff --git a/crates/vork-render/src/render_images.rs b/crates/vork-render/src/render_images.rsindex 1fa2e8b..3277f2b 100644--- a/crates/vork-render/src/render_images.rs+++ b/crates/vork-render/src/render_images.rs@@ -418,7 +418,7 @@ impl CaptureView {if step.pass == crate::graph::Pass::Denoise {if let Some(stage) = &view.post.reconstruction { stage.encode(encoder,None); }if let Some(stage) = &view.post.denoiser {- stage.run(renderer, encoder, view.sample_count, denoise_timing, segments)?;+ stage.run(renderer, encoder, view.sample_count, 1., denoise_timing, segments)?;}} else {crate::graph::encode_view(encoder, view, step, renderer, segments)?;diff --git a/crates/vork-render/src/rt.rs b/crates/vork-render/src/rt.rsindex 58290ed..f939ab7 100644--- a/crates/vork-render/src/rt.rs+++ b/crates/vork-render/src/rt.rs@@ -60,7 +60,6 @@ pub(crate) fn gi_layout(d: &wgpu::Device,materials: &wgpu::BindGroupLayout,probes: bool,- medium: bool,) -> wgpu::PipelineLayout {let entries = gi_entries();let group = d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {@@ -69,17 +68,17 @@ pub(crate) fn gi_layout(});d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {label: Some("ray GI layout"),- bind_group_layouts: &[Some(&group), Some(materials), probes.then(|| crate::probes::read_layout(d)).as_ref(), Some(&gi_read_layout(d,medium))],+ bind_group_layouts: &[Some(&group), Some(materials), probes.then(|| crate::probes::read_layout(d)).as_ref(), Some(&gi_read_layout(d))],immediate_size: 0,})}-pub(crate) fn gi_read_entries(medium:bool)->Vec<wgpu::BindGroupLayoutEntry> {+pub(crate) fn gi_read_entries()->Vec<wgpu::BindGroupLayoutEntry> {let mut entries=vec![hit_buffers_entry(0,wgpu::ShaderStages::COMPUTE)];- if medium {entries.push(pipelines::buffer_entry(1,wgpu::ShaderStages::COMPUTE,wgpu::BufferBindingType::Storage {read_only:false}));}+ entries.push(pipelines::buffer_entry(1,wgpu::ShaderStages::COMPUTE,wgpu::BufferBindingType::Storage {read_only:false}));entries}-pub(crate) fn gi_read_layout(d:&wgpu::Device,medium:bool)->wgpu::BindGroupLayout {- d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {label:Some("GI hit and accumulation buffers"),entries:&gi_read_entries(medium)})+pub(crate) fn gi_read_layout(d:&wgpu::Device)->wgpu::BindGroupLayout {+ d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {label:Some("GI hit and accumulation buffers"),entries:&gi_read_entries()})}/// Group 3 of hit-shading compute kernels: only the hit buffer array (wgpu/// keeps binding arrays out of groups with uniform buffers; group 2 is the@@ -520,10 +519,10 @@ pub(crate) fn normalize_materials(scene: &mut Scene) {for input in ["geometry_opacity", "alpha_cutoff"] {if (input!="alpha_cutoff" || material.program=="std/openpbr") && matches!(material.inputs.get(input), Some(vork_scene::v2::Input::Attribute(_))) {if material.program=="std/openpbr" {+ crate::warnings::dropped("ray_opacity_attribute", serde_json::json!({"material":name,"input":input,"binding":material.inputs.get(input)}), format!("warning: material {name}: ignored named {input} attribute for ray visibility; using the program default"));material.inputs.remove(input);- eprintln!("warning: material {name}: ignored named {input} attribute for ray visibility; using the program default");} else {- eprintln!("warning: material {name}: ignored custom surface with named {input} attribute for ray visibility; using default OpenPBR surface");+ crate::warnings::dropped("ray_surface_attribute", serde_json::json!({"material":name,"surface":material,"input":input,"tracks":scene.animation.iter().flat_map(|layer|layer.tracks.iter().flatten()).filter(|track|matches!(track.path.as_slice(),[root,target,..] if root=="materials" && target==name)).collect::<Vec<_>>()}), format!("warning: material {name}: ignored custom surface and its material animation with named {input} attribute for ray visibility; using default OpenPBR surface"));*material=serde_json::from_value(serde_json::json!({})).expect("default material");discarded.insert(name.clone());break;@@ -877,6 +876,15 @@ fn geometry_key(draw: &install::Draw) -> (wgpu::Buffer,wgpu::Buffer,u64,u64,u32,(draw.vertices.clone(),draw.indices.clone(),draw.vertex_offset,draw.index_offset,draw.count,draw.vertex_count,draw.layout.vertex_stride(),draw.ray_corners.is_some())}+/// A shared position stream still needs separate BLAS for distinct topology or+/// coverage flags. Static geometry retains its installed ownership separately.+fn evaluated_owners(draws: &[install::Draw]) -> Vec<usize> {+ let mut geometries = std::collections::HashMap::new();+ draws.iter().enumerate().map(|(i, draw)| {+ if !draw.evaluated() { return i; }+ *geometries.entry((draw.evaluation_leader().unwrap_or(i), geometry_key(draw))).or_insert(i)+ }).collect()+}fn triangles_size(draw: &install::Draw) -> wgpu::BlasTriangleGeometrySizeDescriptor {triangles(draw.ray_corners.is_some(),draw.vertex_count,draw.count)}@@ -1086,12 +1094,16 @@ impl FrameRays {pub(crate) fn new(s: &InstalledScene, r: &Renderer, objects: &wgpu::Buffer) -> Result<Option<Self>> {let d=&r.device;let Some(installed) = s.rays.as_ref() else {return Ok(None);};+ // Evaluated positions can be shared by draws with different index ranges.+ // Own BLAS by the complete geometry identity, not just the pose leader.+ let owners = evaluated_owners(&s.draws);let deformed: Vec<Option<(wgpu::BlasTriangleGeometrySizeDescriptor, wgpu::Blas)>> = s.draws.iter().zip(&installed.alpha_tested)- .map(|(draw, &alpha_tested)| {- if !draw.evaluated() {return None;}+ .enumerate()+ .map(|(i, (draw, &alpha_tested))| {+ if !draw.evaluated() || owners[i] != i {return None;}let size = triangles(alpha_tested, draw.vertex_count, draw.count);let built = blas(d, "deformed primitive BLAS", &size);Some((size, built))@@ -1108,7 +1120,7 @@ impl FrameRays {let instances:Vec<_>=installed.instances.iter().enumerate().map(|(slot,&(draw,object))| {let blas=visibility_blas.get(&slot).copied().or(installed.blas[draw].as_ref())- .or_else(||deformed[draw].as_ref().map(|(_,b)|b)).expect("ray instance BLAS");+ .or_else(||deformed[owners[draw]].as_ref().map(|(_,b)|b)).expect("ray instance BLAS");(object,!s.materials[s.draws[draw].material].transparent,s.draws[draw].implicit.is_none(),installed.shadow_solids[slot],blas.clone())}).collect();crate::gpu_tlas::Placement::new(r,objects,&instances,&installed.placement_pipeline)@@ -1126,14 +1138,19 @@ pub(crate) fn encode(encoder: &mut wgpu::CommandEncoder, s: &InstalledScene, f:};// The slot's first sample builds everything; later ones follow the uploads.let first = f.changes.changed(values::ChangeKey::RayStructures, &[1]);- let uploads = &f.changes.uploads;- let uploaded = |buffer: &wgpu::Buffer| uploads.iter().any(|u| &u.0 == buffer);+ let uploaded = |buffer: &wgpu::Buffer| f.changes.buffer_dirty(buffer);// CPU subdivision uploads its evaluated poses with fixed skin parameters.// Those vertex changes invalidate the same deformed BLAS as GPU skin/morphs.- let deform_changed = f.computed_geometry.iter().enumerate().any(|(i,g)|g.is_some() && f.changes.dirty(values::ChangeKey::ComputedPositions(i))) || first- || f.skin.iter().flatten().any(|d| uploaded(&d.params))- || f.subdivision_morphs.iter().flatten().any(uploaded)- || f.displacements.iter().flatten().any(|frame|frame.dirty(&f.changes));+ let dirty_geometry: Vec<bool> = s.draws.iter().enumerate().map(|(i, draw)| {+ // Static draws and aliases own no evaluated BLAS to invalidate.+ if rays.deformed[i].is_none() {return false;}+ let i = draw.displacement_leader.unwrap_or(i);+ first || f.changes.dirty(values::ChangeKey::ComputedPositions(i))+ || f.skin[i].as_ref().is_some_and(|d| uploaded(&d.params) || uploaded(&d.previous_params))+ || f.subdivision_morphs[i].as_ref().is_some_and(uploaded)+ || f.displacements.get(i).and_then(|frame| frame.as_ref()).is_some_and(|frame| frame.dirty(&f.changes))+ }).collect();+ let deform_changed = rays.deformed.iter().zip(&dirty_geometry).any(|(blas, dirty)| blas.is_some() && *dirty);let placement_changed = if rays.placement.is_some() {let changed=rays.placement_revision != f.changes.placement_revision;rays.placement_revision=f.changes.placement_revision;@@ -1157,7 +1174,7 @@ pub(crate) fn encode(encoder: &mut wgpu::CommandEncoder, s: &InstalledScene, f:.deformed.iter().enumerate()- .filter(|_| deform_changed)+ .filter(|(index, _)| dirty_geometry[*index]).filter_map(|(index, deformed)| {let (size, blas) = deformed.as_ref()?;let draw = &s.draws[index];diff --git a/crates/vork-render/src/shot.rs b/crates/vork-render/src/shot.rsindex 9826535..f31f15c 100644--- a/crates/vork-render/src/shot.rs+++ b/crates/vork-render/src/shot.rs@@ -198,6 +198,8 @@ impl Shot {}pub(crate) fn render_scoped<'scope>(self, scope: &'scope std::thread::Scope<'scope, '_>) -> Result<RenderedShot> {+ let warnings = crate::warnings::Collector::default();+ let _warning_scope = warnings.enter();let wall = Instant::now();let Self {scene: scene_path,@@ -437,6 +439,7 @@ impl Shot {Ok((prepared, start.elapsed().as_secs_f64() * 1000.))})});+ vork_slang::progress::phase("Render: preparing scene, shaders and encoder", 0);let renderer = match device_worker.join().map_err(|_| anyhow::anyhow!("device creation worker panicked"))@@ -452,9 +455,6 @@ impl Shot {return Err(error);}};- if renderer.shader_cache_cold() {- eprintln!("Shader cache is cold for this vork/GPU driver; first renders compile shaders. Run `vork setup` once to precompile (about a minute on Linux).");- }if diagnostics {eprintln!("device: {:?}; pipeline cache supported: {}",@@ -467,6 +467,7 @@ impl Shot {let (installed, encoders, encoder_prepare_ms, encoder_attach_ms) =std::thread::scope(|scope| -> Result<_> {let install = scope.spawn(|| {+ let _warning_scope = warnings.enter();let mut scene = scene;if let Some((profile, level, keep_samples)) = &default_denoise {crate::denoise::resolve_default(&renderer, &mut scene, profile, *level, *keep_samples);@@ -592,6 +593,7 @@ impl Shot {let png_workers: usize = png_outputs.iter().map(|p| p.worker_count).sum();let mut foreground = Some(foreground);let ready_ms = wall.elapsed().as_secs_f64() * 1000.;+ vork_slang::progress::phase("Rendering frames", frames);let loop_start = Instant::now();let mut samples = Vec::new();let mut metadata_frames = Vec::new();@@ -694,7 +696,9 @@ impl Shot {for writer in &png_outputs { writer.push(index(frame), p.clone())?; }}frame += 1;+ vork_slang::progress::completed(frame);}+ vork_slang::progress::phase("Render: finishing encoders and writing files", 0);let finish_start = Instant::now();for encoder in &mut encoders {encoder.finish().map_err(device)?;@@ -705,6 +709,7 @@ impl Shot {0.};if still_pass {+ vork_slang::progress::phase("Rendering selected still", 1);let still_frame = (at.unwrap() * fps).round() as usize;let pixels = loop {let slot = &mut slots[0];@@ -721,6 +726,7 @@ impl Shot {}}};+ vork_slang::progress::completed(1);still_exposure = pixels.exposure;still_camera = Some(pixels.camera);for writer in &png_outputs {@@ -730,6 +736,7 @@ impl Shot {Ok((encoder_finish_ms, memory_frames))})();let mut output_result = Ok(());+ vork_slang::progress::phase("Render: writing files and reports", 0);for writer in png_outputs {let result = writer.finish();if output_result.is_ok() { output_result = result; }@@ -742,11 +749,14 @@ impl Shot {let save_start = Instant::now();renderer.save_idle_pipelines().map_err(device)?;let pipeline_save_ms = save_start.elapsed().as_secs_f64() * 1000.;+ let mut sidecars = Vec::new();for path in &video_paths {+ let camera_path = sidecar(path, "camera.json");std::fs::write(- sidecar(path, "camera.json"),+ &camera_path,serde_json::to_vec_pretty(&crate::camera::clip(&camera_frames, fps, Some(first_frame))?)?,)?;+ sidecars.push(camera_path);}if outputs.has(Output::Camera) && !no_write && !gpu_only {let frames = still_camera@@ -763,7 +773,8 @@ impl Shot {if let Some(parent) = camera_path.parent() {std::fs::create_dir_all(parent)?;}- std::fs::write(camera_path, &bytes)?;+ std::fs::write(&camera_path, &bytes)?;+ sidecars.push(camera_path);}}if implicit_still && !no_write && !gpu_only {@@ -788,6 +799,7 @@ impl Shot {let metadata = |frames: &[serde_json::Value]| serde_json::json!({"version": 1, "fps": fps, "frames": frames,"object_ids": &*installed.object_ids,+ "warnings": warnings.snapshot(),"profile": profile_record, "settings": installed.render().settings,"denoiser": installed.render().settings.integrator.denoiser().and_then(|_| crate::denoise::device_kind(&renderer)),});@@ -816,11 +828,16 @@ impl Shot {meta["exposure"] = summary.clone();exposures.push(serde_json::json!({"output": path, "exposure": summary}));}- std::fs::write(meta_path, serde_json::to_vec_pretty(&meta)?)?;+ std::fs::write(&meta_path, serde_json::to_vec_pretty(&meta)?)?;+ sidecars.push(meta_path);if diagnostics {- std::fs::write(file_path("timings.json"), serde_json::to_vec_pretty(&report)?)?;+ let timing_path = file_path("timings.json");+ std::fs::write(&timing_path, serde_json::to_vec_pretty(&report)?)?;+ sidecars.push(timing_path);}}+ report["warnings"] = serde_json::to_value(warnings.snapshot())?;+ report["sidecars"] = serde_json::to_value(sidecars)?;report["exposure"] = exposures.into();Ok(RenderedShot {report,diff --git a/crates/vork-render/src/slang_forward.rs b/crates/vork-render/src/slang_forward.rsindex 07e79bd..5f68810 100644--- a/crates/vork-render/src/slang_forward.rs+++ b/crates/vork-render/src/slang_forward.rs@@ -240,8 +240,12 @@ impl SlangForward {if stage.composes() && self.msaa {kernel_defines.push("-DVORK_RASTER_MSAA".into());}}- // Bound the path optimization graph on both native backends. Vulkan's- // SPIR-V handoff restores driver inlining; Metal keeps these boundaries.+ // Bound the lighting graph for triangle-only Vulkan GI and the path graph+ // on both native backends. Vulkan restores driver inlining at the+ // SPIR-V handoff; Metal keeps these boundaries.+ let surface_outlining = !self.metal && !self.scene.field_controls && self.scene.medium.is_none()+ && matches!(kernel, Some(ProgramKernel::Gi {..}));+ if surface_outlining {kernel_defines.push("-DVORK_SURFACE_SLANG_OUTLINE".into());}let path_outlining = matches!(kernel, Some(ProgramKernel::Path {..}));if path_outlining {kernel_defines.extend([NATIVE_OPTIMIZATION.to_owned(), "-DVORK_PATH_SLANG_OUTLINE".into()]);@@ -376,6 +380,67 @@ impl SlangForward {match main { "decoupled_programs" => Some(15), _ => None }} else {None};let denoise=self.scene.denoise && matches!(entry.0,"controls_fs"|"transparent_controls_fs");+ let mut modules = native::SOURCES.to_vec();+ for (name, source) in &program_modules {+ if let Some(module)=modules.iter_mut().find(|(n,_)|*n==name) {*module=(name,source);} else {modules.push((name,source));}+ }+ if let Some(text) = text {+ modules.push((main, text));+ }+ let mut include: Vec<String> = if secondary {all_programs} else {programs}+ .map_or(&[][..], |p| &p.include[..])+ .iter()+ .map(|d| d.display().to_string())+ .collect();+ if let Some(environment)=&self.scene.environment {include.extend(environment.include.iter().map(|p|p.display().to_string()));}+ if let Some(p)=&self.scene.propagation {include.extend(p.include.iter().map(|p|p.display().to_string()));}+ if let Some(camera)=&self.scene.camera {include.extend(camera.include.iter().map(|p|p.display().to_string()));}+ if let Some(native)=path_medium.or(refraction_medium).or(reflection_medium).or(diffuse_medium).or(surface_medium) {include.extend(native.includes.iter().map(|p|p.display().to_string()));}+ let query_defines:Vec<_> = if self.metal && entry.1=="vertex" {+ vec!["-DVORK_MATERIAL_WORDS_REGISTER=t2","-DVORK_FRAME_LIGHTS_REGISTER=t30"]+ }else{Vec::new()};+ let kernel_module = match main {+ "gi_programs" => "gi_ray",+ "reflections_programs" => "reflections_hits", "probe_programs" => "probe_update",+ "path_programs_main" | "path_programs_fixed" => "path", _ => "",+ };+ let mut native_registers = if self.metal {+ crate::forward_variant::hit_kernel_registers(kernel_module,+ adaptive,+ main == "probe_programs" || (self.scene.probes && matches!(main,"gi_programs"|"reflections_programs")))+ } else {Vec::new()};+ if let Some(first) = probe_register {+ native_registers.extend(crate::forward_variant::probe_registers(first));+ }+ let args: Vec<&str> = ["-target", target]+ .into_iter()+ .chain(SLANG_FLAGS.iter().copied())+ .chain(flags.iter().copied())+ .chain(native_registers.iter().map(String::as_str))+ .chain(program_coverage.then_some("-DVORK_PROGRAM_COVERAGE"))+ .chain(kernel_defines.iter().map(String::as_str))+ .chain(query_defines.iter().copied())++ .chain(visibility_medium.is_some().then_some("-DVORK_VOLUME_VISIBILITY"))+ .chain((self.ray_shadows || (main=="decoupled_programs" && self.scene.ray_refraction)).then_some("-DVORK_RAY_BINDINGS"))+ .chain((main=="decoupled_programs" && self.scene.ray_refraction).then_some("-DVORK_RAY_REFRACTION"))+ .chain(denoise.then_some("-DVORK_DENOISE"))+ .chain(probes.then_some("-DVORK_PROBES"))+ .chain(fibre.then_some("-DVORK_FIBRE"))+ .chain(fibre.then_some(fibre_binding))+ .chain(probes.then_some(probe_binding.as_str()))+ .chain((self.scene.attributes > 0).then_some(define.as_str()))+ .chain(include.iter().flat_map(|d| ["-I", d.as_str()]))+ .collect();+ let compiler=vork_slang::Compiler::discover();+ let identities=(if secondary {all_programs} else {programs}).map(|p|p.identities.clone()).unwrap_or_default();+ let (identity,prepared)=if probe {+ let Some(identity)=programs::cached_native_input_identity(self.cache.as_ref(),&compiler,&modules,main,&[entry],&args,&identities)? else {return Ok(Lookup::Absent);};+ (identity,None)+ } else {+ programs::native_input_identity(self.cache.as_ref(),&compiler,&modules,main,&[entry],&args,&identities)?+ };+ if let Some(programs)=if secondary {all_programs} else {programs} {for input in &programs.inputs {identity.verify(input)?;}}let mut hash = blake3::Hasher::new();if self.scene.field_controls {hash.update(b"field-driver-inline-v1");}if refraction_medium.is_some() || reflection_medium.is_some() || diffuse_medium.is_some() || surface_medium.is_some() {hash.update(b"medium-driver-inline-v1");}@@ -393,74 +458,20 @@ impl SlangForward {if fibre {hash.update(fibre_binding.as_bytes());}// Embedded renderer modules and compiler inputs have a shader-only// content identity in the store, independent of host builds/devices.- for (name, source) in &program_modules {- hash.update(name.as_bytes());- hash.update(source.as_bytes());- }+ hash.update(&identity.identity);let path = (self.cache)(hash.finalize());if probe {return Ok(if disk_cache::read(&path).is_some() {Lookup::Stored} else {Lookup::Absent});}let code = match disk_cache::read(&path) {Some(code) => code,None => {- let mut modules = native::SOURCES.to_vec();- for (name, source) in &program_modules {- if let Some(module)=modules.iter_mut().find(|(n,_)|*n==name) {*module=(name,source);} else {modules.push((name,source));}- }- if let Some(text) = text {- modules.push((main, text));- }- let mut include: Vec<String> = if secondary {all_programs} else {programs}- .map_or(&[][..], |p| &p.include[..])- .iter()- .map(|d| d.display().to_string())- .collect();- if let Some(environment)=&self.scene.environment {include.extend(environment.include.iter().map(|p|p.display().to_string()));}- if let Some(p)=&self.scene.propagation {include.extend(p.include.iter().map(|p|p.display().to_string()));}- if let Some(camera)=&self.scene.camera {include.extend(camera.include.iter().map(|p|p.display().to_string()));}- if let Some(native)=path_medium.or(refraction_medium).or(reflection_medium).or(diffuse_medium).or(surface_medium) {include.extend(native.includes.iter().map(|p|p.display().to_string()));}- let query_defines:Vec<_> = if self.metal && entry.1=="vertex" {- vec!["-DVORK_MATERIAL_WORDS_REGISTER=t2","-DVORK_FRAME_LIGHTS_REGISTER=t30"]- }else{Vec::new()};- let kernel_module = match main {- "gi_programs" => "gi_ray",- "reflections_programs" => "reflections_hits", "probe_programs" => "probe_update",- "path_programs_main" | "path_programs_fixed" => "path", _ => "",- };- let mut native_registers = if self.metal {- crate::forward_variant::hit_kernel_registers(kernel_module,- adaptive,- main == "probe_programs" || (self.scene.probes && matches!(main,"gi_programs"|"reflections_programs")))- } else {Vec::new()};- if let Some(first) = probe_register {- native_registers.extend(crate::forward_variant::probe_registers(first));- }- let args: Vec<&str> = ["-target", target]- .into_iter()- .chain(SLANG_FLAGS.iter().copied())- .chain(flags.iter().copied())- .chain(native_registers.iter().map(String::as_str))- .chain(program_coverage.then_some("-DVORK_PROGRAM_COVERAGE"))- .chain(kernel_defines.iter().map(String::as_str))- .chain(query_defines.iter().copied())-- .chain(visibility_medium.is_some().then_some("-DVORK_VOLUME_VISIBILITY"))- .chain((self.ray_shadows || (main=="decoupled_programs" && self.scene.ray_refraction)).then_some("-DVORK_RAY_BINDINGS"))- .chain((main=="decoupled_programs" && self.scene.ray_refraction).then_some("-DVORK_RAY_REFRACTION"))- .chain(denoise.then_some("-DVORK_DENOISE"))- .chain(probes.then_some("-DVORK_PROBES"))- .chain(fibre.then_some("-DVORK_FIBRE"))- .chain(fibre.then_some(fibre_binding))- .chain(probes.then_some(probe_binding.as_str()))- .chain((self.scene.attributes > 0).then_some(define.as_str()))- .chain(include.iter().flat_map(|d| ["-I", d.as_str()]))- .collect();- let entries=vec![entry];let start=std::time::Instant::now();- let mut code = vork_slang::Compiler::discover().compile_modules(&modules,main,&entries,&args)?;+ let prepared=match prepared {Some(input)=>input,None=>compiler.prepare_identified_modules(&modules,main,&[entry],&args,&identities)?};+ anyhow::ensure!(prepared.identity()==identity.identity,"Slang inputs changed during cache lookup; retry the command");+ let mut code = prepared.compile()?;if self.metal && matches!(kernel,Some(ProgramKernel::Decoupled {stage:ShadeStage::Evaluate,..})) {code=crate::camera_native::inline_metal_functions(&code);}- if (self.scene.field_controls || path_outlining || refraction_medium.is_some() || reflection_medium.is_some() || diffuse_medium.is_some() || surface_medium.is_some()) && !self.metal { allow_driver_inlining(&mut code)?; }+ if (self.scene.field_controls || surface_outlining || path_outlining || refraction_medium.is_some() || reflection_medium.is_some() || diffuse_medium.is_some() || surface_medium.is_some()) && !self.metal { allow_driver_inlining(&mut code)?; }crate::timing::creation(&self.device,label,"Slang",start.elapsed().as_secs_f64()*1000.,0.);let _ = disk_cache::write(&path, &code);code@@ -545,6 +556,9 @@ impl SlangForward {/// transport (ray refraction, program shadow coverage, fibres) can reach one./// Then no table kernel grows with the scene's program count.fn table_programs(&self,kernel:Option<crate::pipelines::ProgramKernel>)->Option<&programs::Native> {+ // Composition consumes stored closures and explicitly calls NoPrograms.+ // Do not import the scene dispatcher merely to define an unused type.+ if matches!(kernel,Some(crate::pipelines::ProgramKernel::Decoupled {stage:crate::pipelines::ShadeStage::Compose,..})) {return None;}let table=matches!(kernel,Some(crate::pipelines::ProgramKernel::Decoupled {stage,..}) if stage.table());self.scene.programs.as_deref().filter(|_|!table || self.transport_programs())}diff --git a/crates/vork-render/src/std_warm.rs b/crates/vork-render/src/std_warm.rsindex 74b352e..ff7e323 100644--- a/crates/vork-render/src/std_warm.rs+++ b/crates/vork-render/src/std_warm.rs@@ -220,16 +220,26 @@ fn prepare(mut value: serde_json::Value, mut settings: v2::Settings) -> Result<v/// sampled world medium) is one no render compiles: setup skips it.fn run(r: &Renderer, jobs: impl Iterator<Item = (serde_json::Value, v2::Settings)>, options: InstallOptions) -> Result<()> {let jobs = std::sync::Mutex::new(jobs.collect::<Vec<_>>().into_iter());+ vork_slang::progress::phase("Setup: warming configurations", jobs.lock().unwrap().len());+ let completed = std::sync::atomic::AtomicUsize::new(0);let workers = std::thread::available_parallelism().map_or(1, usize::from).min(4);std::thread::scope(|scope| {let workers: Vec<_> = (0..workers).map(|_| scope.spawn(|| -> Result<()> {loop {let Some((scene, integrator)) = jobs.lock().unwrap().next() else { break };let name = scene["materials"]["std"]["program"].as_str().unwrap_or("built-in materials").to_owned();+ let explicit_camera = scene["nodes"].as_array().unwrap().iter()+ .any(|node| node["type"] == "camera" && !node["material"].is_null());+ // The explicit standard-camera jobs retain the broad hit keys.+ // Ordinary table jobs warm the smaller material-compatible keys+ // through the same install constructors, without extra installs.+ let variants = if explicit_camera && matches!(options.variants, pipelines::VariantCompile::SetupPlain) {+ pipelines::VariantCompile::Setup+ } else { options.variants.clone() };let compile = || -> Result<()> {let scene = prepare(scene, integrator)?;let installed = r.install_with_options(scene, Path::new("."), InstallOptions {- variants: options.variants.clone(), ..Default::default() })?;+ variants, ..Default::default() })?;// Volume, resolve and composite pipelines belong to the frame slot.let _frame = installed.create_frame_slot(r, Default::default())?;Ok(())@@ -238,6 +248,7 @@ fn run(r: &Renderer, jobs: impl Iterator<Item = (serde_json::Value, v2::SettingsErr(error) if crate::failure::is_scene(&error) => {}result => result.with_context(|| format!("setup pipelines for {name}"))?,}+ vork_slang::progress::completed(completed.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1);}Ok(())})).collect();@@ -273,10 +284,11 @@ pub(crate) fn warm_startup(r: &Renderer) -> Result<()> {(scene,settings.clone())}).collect();jobs.extend(camera_jobs);- run(r,jobs.into_iter(), InstallOptions {variants:pipelines::VariantCompile::Setup,..Default::default()})+ run(r,jobs.into_iter(), InstallOptions {variants:pipelines::VariantCompile::SetupPlain,..Default::default()})}pub(crate) fn warm(r: &Renderer) -> Result<()> {+ warm_startup(r)?;let mut all = table_scenes(r);all.extend(scenes(r, vork_scene::libraries::prebuilt_programs())?);compile(r, &all)@@ -286,6 +298,55 @@ pub(crate) fn warm(r: &Renderer) -> Result<()> {mod tests {use super::*;+ #[test]+ fn startup_plain_hits_match_exact_specializations() -> Result<()> {+ for metalness in [0., 1.] {+ // Adapter-free runners skip with test_renderer's diagnostic; renderer+ // failures and actual hit-selection/pixel assertions still fail on a GPU.+ let Some(mut r) = crate::test_renderer()? else { return Ok(()) };+ // Isolate the device-key catalogue from disk and other tests. Setup+ // must be the sole source of known keys for the first install.+ let keys=r.disk_cache.path("test-plain-hit-keys",1,blake3::hash(b""));+ r.compiler = pipelines::Compiler::new(&r.device, r.cache.as_ref(), pipelines::Known::load(keys,false));+ r.warm_startup_shaders()?;+ let mut scene = crate::test_scene(serde_json::json!({"version":2,+ "render":{"resolution":[64,48]},+ "nodes":[+ {"type":"mesh","geometry":{"std":"sphere"},"materials":[{"inputs":{"base_color":[0.2,0.4,0.7],"base_metalness":metalness,"specular_roughness":0.3}}]},+ {"type":"mesh","translation":[0,-1,0],"geometry":{"std":"grid","size":[8,8]}},+ {"type":"camera","translation":[3,2,5],"target":[0,0,0]},+ {"type":"light","shape":"rectangle","translation":[-3,5,4],"target":[0,0,0],"energy":500,"size":3},+ {"type":"light","shape":"sun","energy":0.1},+ {"type":"light","shape":"point","translation":[2,3,2],"energy":10},+ {"type":"light","shape":"spot","translation":[0,4,0],"target":[0,0,0],"energy":10}+ ]}), Path::new("."))?;+ scene.render.settings = v2::Profile::load(v2::DEFAULT_PROFILE)?.resolve(+ &serde_json::from_value(serde_json::json!({"denoise":false}))?)?;+ let draw = |mode, expect_plain| -> Result<Vec<[f32;4]>> {+ r.compiler.hit_selections.lock().unwrap().clear();+ let mut installed = r.install_with_options(scene.clone(), Path::new("."), InstallOptions { variants: mode, ..Default::default() })?;+ let selections = r.compiler.hit_selections.lock().unwrap().clone();+ for is_gi in [true,false] {+ let hits: Vec<_> = selections.iter().filter(|(requested,_)| if is_gi {+ matches!(requested,pipelines::ProgramKernel::Gi {..})+ } else {matches!(requested,pipelines::ProgramKernel::Reflections {..})}).collect();+ assert_eq!(hits.len(),1,"must observe the installed hit pipeline: {selections:?}");+ let (requested,selected)=*hits[0];+ let plain=requested.plain_hit().expect("plain-compatible scene");+ assert_ne!(requested,plain,"scene must distinguish exact and plain keys");+ assert_eq!(selected,if expect_plain {plain} else {requested},"actual installed hit selection");+ }+ let mut slot = installed.create_frame_slot(&r, ReadbackPrecision::Float)?;+ installed.render_frame(&r, &mut slot, 0.)?.linear_rgba.context("float readback")+ };+ let plain = draw(pipelines::VariantCompile::Background, true)?;+ r.settle_pipelines()?;+ let exact = draw(pipelines::VariantCompile::Inline, false)?;+ assert_eq!(plain, exact, "metalness {metalness}: setup hit evaluator changed the frame");+ }+ Ok(())+ }+#[test]fn setup_covers_draft_and_final_oidn_and_off_at_shipped_camera_budgets() -> Result<()> {let settings = configurations()?;@@ -366,10 +427,13 @@ mod tests {fn every_std_program_has_a_role() {let roles: Vec<_> = vork_scene::libraries::prebuilt_programs().map(|name| (name, role(vork_slang::module_source(name).unwrap()))).collect();- for (name, expected) in [("std/sky", Role::Environment), ("std/fog", Role::Medium), ("std/bloom", Role::Composite),+ for (name, expected) in [("std/sky", Role::Environment), ("std/bloom", Role::Composite),("std/hair", Role::Hair), ("std/camera",Role::Camera), ("std/environment_image",Role::Environment)] {assert!(roles.contains(&(name, expected)), "{name}: {roles:?}");}+ // Medium programs are authored on demand and absent from the shipped+ // catalog; role detection must still recognize their entry signature.+ assert_eq!(role("MediumCoefficients medium(MediumContext ctx) {}"), Role::Medium);// blender and post programs compile on first use.assert!(roles.iter().all(|(name, _)| name.starts_with("std/")), "{roles:?}");}@@ -474,7 +538,7 @@ mod tests {// Any std/sky world now finds its compiled program; only its input words differ.let source = vork_slang::module_source("std/sky").context("std/sky module")?;let key = environment_program::program_key(&programs::abi(), source, Path::new("std/sky.slang"))?;- programs::cached(&r, key, |p: &vork_slang::EnvironmentProgram| &p.dependencies, || bail!("std/sky compiled again"))?;+ let _:vork_slang::EnvironmentProgram=programs::cached(&r, key, &vork_slang::Compiler::discover(), &programs::abi(), source, Path::new("std/sky.slang"), |_| bail!("std/sky compiled again"))?;let scene: v2::Scene = serde_json::from_value(serde_json::json!({"version": 2,"nodes": [{"type": "light", "shape": "environment", "material": "sky"}],"materials": {"sky": {"program": "std/sky", "inputs": {"sun_elevation": 0.5, "altitude": 10}}}}))?;diff --git a/crates/vork-render/src/texture_source.rs b/crates/vork-render/src/texture_source.rsindex bcfa634..fa18a9a 100644--- a/crates/vork-render/src/texture_source.rs+++ b/crates/vork-render/src/texture_source.rs@@ -109,6 +109,7 @@ mod tests {/// harness's format selector). Each aborted, panicked, took gigabytes or ran for/// tens of seconds; each is now refused with its cause or returns its panic.#[test]+ #[cfg(vork_private_tests)]fn malformed_images_are_refused_before_decoding_or_contained() {let seeds = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../vork-fuzz/seeds/image");let mut cases = vec![diff --git a/crates/vork-render/src/values.rs b/crates/vork-render/src/values.rsindex d8e3e87..cc63b78 100644--- a/crates/vork-render/src/values.rs+++ b/crates/vork-render/src/values.rs@@ -39,6 +39,9 @@ pub(crate) enum ChangeKey {ImageClock(String),/// The frame slot's acceleration structures have had their first build.RayStructures,+ /// Logical displacement evaluation, independent of its packed control page.+ Displacement(usize),+ DisplacedPositions(usize),ComputedGeometry(usize),ComputedPositions(usize),/// Source publication consumed by an installed shared field index.@@ -118,13 +121,24 @@ impl ChangeTracker {/// Canonical value history, independent of the frame slot's buffer identity./// Validity matters: the first write of zero can replace a nonzero installed value.pub(crate) fn append_buffer_inputs(&self, buffer: &wgpu::Buffer, inputs: &mut Vec<u8>) {- let history = self.history.get(&ChangeKey::Buffer(buffer.clone()));+ self.append_inputs(ChangeKey::Buffer(buffer.clone()), inputs);+ }+ pub(crate) fn append_inputs(&self, key: ChangeKey, inputs: &mut Vec<u8>) {+ let history = self.history.get(&key);inputs.extend_from_slice(&(history.map_or(0, |h| h.bytes.len()) as u64).to_le_bytes());if let Some(history) = history {inputs.extend_from_slice(&history.bytes);inputs.extend(history.valid.iter().map(|v| u8::from(*v)));}}+ /// Publish a derived resource without inventing a second dirty mechanism.+ pub(crate) fn publish(&mut self, key: ChangeKey) {+ self.history.entry(key).or_default().stamp = self.sample;+ }+ /// Upload publication and logical changes share one sample generation.+ pub(crate) fn buffer_dirty(&self, buffer: &wgpu::Buffer) -> bool {+ self.dirty(ChangeKey::Buffer(buffer.clone()))+ }pub(crate) fn dirty(&self, key: ChangeKey) -> bool { self.history.get(&key).is_some_and(|h|h.stamp == self.sample) }pub(crate) fn changed(&mut self, key: ChangeKey, bytes: &[u8]) -> bool {let history = self.history.entry(key).or_default();@@ -163,6 +177,7 @@ impl ChangeTracker {if !history.changed(offset as usize, bytes) {return;}+ history.stamp = self.sample;self.record_upload(buffer, offset, bytes);}fn record_upload(&mut self, buffer: &wgpu::Buffer, offset: u64, bytes: &[u8]) {@@ -1310,6 +1325,40 @@ mod orientation_tests {#[cfg(test)]mod upload_cache_tests {use super::UploadCache;+ #[test]+ fn upload_publication_survives_merging_and_drain_until_the_next_sample() {+ let (device, _) = wgpu::Device::noop(&Default::default());+ let buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: None, size: 16, usage: wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let other = device.create_buffer(&wgpu::BufferDescriptor {+ label: None, size: 16, usage: wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let mut changes = super::ChangeTracker::default();+ changes.sample = 1;+ assert!(!changes.buffer_dirty(&buffer));+ changes.upload(&buffer, 4, &[0; 4]); // First zero write is a publication.+ changes.upload(&buffer, 8, &[1; 4]); // Adjacent ranges merge.+ assert_eq!(changes.uploads.len(), 1);+ assert!(changes.buffer_dirty(&buffer));+ assert!(!changes.buffer_dirty(&other));+ changes.uploads.clear(); // Submission takes the work list, not its history.+ changes.bytes.clear();+ assert!(changes.buffer_dirty(&buffer));+ changes.sample += 1;+ changes.upload(&buffer, 4, &[0; 4]);+ assert!(!changes.buffer_dirty(&buffer));+ assert!(changes.uploads.is_empty());+ changes.upload(&buffer, 6, &[2; 4]); // Partial overlap.+ changes.upload(&buffer, 6, &[2; 4]); // Unchanged write cannot clear dirty.+ assert!(changes.buffer_dirty(&buffer));+ assert_eq!(changes.uploads.len(), 1);+ changes.sample += 1;+ assert!(!changes.buffer_dirty(&buffer));+ }+#[test]fn partial_overlaps_and_first_zero_writes_remain_dirty() {let mut cache = UploadCache::default();diff --git a/crates/vork-render/src/warnings.rs b/crates/vork-render/src/warnings.rsnew file mode 100644index 0000000..61af5bb--- /dev/null+++ b/crates/vork-render/src/warnings.rs@@ -0,0 +1,100 @@+//! Visible losses are render results, not debug logging. A shot owns its collector;+//! installation workers explicitly inherit it, so concurrent shots stay isolated.+use std::{cell::RefCell, sync::{Arc, Mutex}};+use serde::Serialize;++#[derive(Clone, Debug, PartialEq, Serialize)]+pub struct RenderWarning {+ pub code: &'static str,+ /// Authored object, program, binding or value that requested the effect.+ pub requested: serde_json::Value,+ /// Exactly what was omitted or substituted, including the retained behaviour.+ pub dropped: String,+}+#[derive(Clone, Default)]+pub(crate) struct Collector(Arc<Mutex<Vec<RenderWarning>>>);+thread_local! { static CURRENT: RefCell<Option<Collector>> = const { RefCell::new(None) }; }+pub(crate) struct Guard(Option<Collector>);+impl Drop for Guard {+ fn drop(&mut self) { CURRENT.with(|c| *c.borrow_mut() = self.0.take()); }+}+impl Collector {+ pub(crate) fn enter(&self) -> Guard {+ Guard(CURRENT.with(|c| c.replace(Some(self.clone()))))+ }+ pub(crate) fn current() -> Option<Self> { CURRENT.with(|c| c.borrow().clone()) }+ pub(crate) fn snapshot(&self) -> Vec<RenderWarning> { self.0.lock().unwrap().clone() }+}+pub(crate) fn dropped(code: &'static str, requested: serde_json::Value, dropped: String) {+ let warning = RenderWarning { code, requested, dropped };+ let fresh = CURRENT.with(|current| {+ let collector = current.borrow();+ let Some(collector) = collector.as_ref() else { return true };+ let mut warnings = collector.0.lock().unwrap();+ if warnings.contains(&warning) { false } else { warnings.push(warning.clone()); true }+ });+ if fresh {+ // No ANSI or TTY detection: the same conspicuous record survives logs.+ eprintln!("\nWARNING: REQUESTED EFFECT DROPPED [{}]\n requested: {}\n dropped: {}\n", warning.code, warning.requested, warning.dropped);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn identical_unnamed_environments_keep_distinct_authored_locations() {+ let scene = vork_scene::v2::Scene::from_json(br#"{"version":2,"nodes":[{"type":"camera"},{"type":"light","shape":"environment"},{"type":"light","shape":"environment"},{"type":"light","shape":"environment"}]}"#).unwrap();+ let collector = Collector::default();+ let _scope = collector.enter();+ let settings = crate::environment_node::Settings::from_scene(&scene).unwrap();+ assert_eq!(settings.source, Some(1));+ let warnings = collector.snapshot();+ assert_eq!(warnings.len(), 2);+ assert_eq!(warnings[0].requested["node_index"], 2);+ assert_eq!(warnings[1].requested["node_index"], 3);+ }++ #[test]+ fn replaced_ray_surface_reports_its_authored_animation_before_removing_it() {+ let mut scene = vork_scene::v2::from_test_value(serde_json::json!({+ "version":2,"nodes":[{"type":"camera"}],+ "render":{"duration":1,"settings":{"integrator":"path"}},+ "materials":{"animated":{"program":{"source":"struct Inputs {float amount=0.;}; Closure surface(ShadingContext c,Inputs i) {Closure s={};return s;}"},+ "inputs":{"geometry_opacity":{"attribute":"alpha"},"amount":0}}},+ "animation":[{"tracks":[{"path":["materials","animated","inputs","amount"],"keys":[[0,0],[1,2]]}]}]+ })).unwrap();+ let collector = Collector::default();+ let _scope = collector.enter();+ crate::rt::normalize_materials(&mut scene);+ assert!(scene.animation[0].tracks.as_ref().unwrap().is_empty());+ let warnings = collector.snapshot();+ assert_eq!(warnings.len(), 1);+ assert_eq!(warnings[0].code, "ray_surface_attribute");+ assert_eq!(warnings[0].requested["tracks"][0]["path"][1], "animated");+ assert_eq!(warnings[0].requested["surface"]["inputs"]["geometry_opacity"]["attribute"], "alpha");+ }++ #[test]+ fn collectors_isolate_shots_and_inherit_workers_without_duplicate_records() {+ let first = Collector::default();+ let _scope = first.enter();+ dropped("test", serde_json::json!({"node":"a","stage":"lit"}), "lit stage; retaining surface".into());+ let worker = Collector::current().unwrap();+ std::thread::spawn(move || {+ let _scope = worker.enter();+ dropped("test", serde_json::json!({"node":"a","stage":"lit"}), "lit stage; retaining surface".into());+ }).join().unwrap();+ let second = Collector::default();+ { let _scope = second.enter(); dropped("other", serde_json::json!({"node":"b"}), "displacement".into()); }+ assert_eq!(first.snapshot().len(), 1);+ assert_eq!(second.snapshot().len(), 1);+ assert_eq!(first.snapshot()[0].requested["stage"], "lit");+ assert_eq!(serde_json::to_value(first.snapshot()).unwrap()[0]["code"], "test");+ }+}++pub(crate) fn additional_environment(node: &vork_scene::v2::Node, first: &str, index: usize) {+ dropped("additional_environment", serde_json::json!({"node": node, "node_index":index, "retained_environment":first}),+ format!("additional environment light at node {index} ({:?}) and its light-property tracks; retaining first environment {first}", node.name));+}diff --git a/crates/vork-render/tests/fixtures/analytic.json b/crates/vork-render/tests/fixtures/analytic.jsonnew file mode 100644index 0000000..8394b4c--- /dev/null+++ b/crates/vork-render/tests/fixtures/analytic.json@@ -0,0 +1,262 @@+{+ "version": 2,+ "render": {+ "resolution": [96,64],+ "fps": 4,+ "duration": 0.75+ },+ "nodes": [+ {"name":"camera","type":"camera","translation":[0,0,5],"rotation":[0,0,0,1],"children":[],"material":{"program":"std/camera","inputs":{"projection":"ortho","ortho_scale":6.0,"clip_start":1,"clip_end":10}}},+ {+ "name": "box",+ "type": "mesh",+ "children": [],+ "geometry": "shape_box"+ },+ {+ "name": "sphere",+ "type": "mesh",+ "translation": [1.5,0,-1],+ "scale": [0.5,0.5,0.5],+ "children": [],+ "geometry": "shape_sphere"+ },+ {+ "name": "plane",+ "type": "mesh",+ "translation": [0,0,-2],+ "rotation": [0.70710678,0,0,0.70710678],+ "scale": [4,1,2],+ "children": [],+ "geometry": "shape_plane"+ },+ {"type":"light","rotation":[-0.27465674831720593,0.1538564517177697,0.044570654466371644,0.9481061752931873],"name":"node","children":[],"shape":"sun","energy":3}+ ],+ "buffers": {+ "shape_box_indices": {+ "type": "u32",+ "data": [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35]+ },+ "shape_box_normal": {+ "type": "vec3",+ "data": [+ [1,0,0],+ [1,0,0],+ [1,0,0],+ [1,0,0],+ [1,0,0],+ [1,0,0],+ [-1,0,0],+ [-1,0,0],+ [-1,0,0],+ [-1,0,0],+ [-1,0,0],+ [-1,0,0],+ [0,1,0],+ [0,1,0],+ [0,1,0],+ [0,1,0],+ [0,1,0],+ [0,1,0],+ [0,-1,0],+ [0,-1,0],+ [0,-1,0],+ [0,-1,0],+ [0,-1,0],+ [0,-1,0],+ [0,0,1],+ [0,0,1],+ [0,0,1],+ [0,0,1],+ [0,0,1],+ [0,0,1],+ [0,0,-1],+ [0,0,-1],+ [0,0,-1],+ [0,0,-1],+ [0,0,-1],+ [0,0,-1]+ ]+ },+ "shape_box_position": {+ "type": "vec3",+ "data": [+ [0.5,-0.5,0.5],+ [0.5,-0.5,-0.5],+ [0.5,0.5,-0.5],+ [0.5,-0.5,0.5],+ [0.5,0.5,-0.5],+ [0.5,0.5,0.5],+ [-0.5,-0.5,-0.5],+ [-0.5,-0.5,0.5],+ [-0.5,0.5,0.5],+ [-0.5,-0.5,-0.5],+ [-0.5,0.5,0.5],+ [-0.5,0.5,-0.5],+ [-0.5,0.5,0.5],+ [0.5,0.5,0.5],+ [0.5,0.5,-0.5],+ [-0.5,0.5,0.5],+ [0.5,0.5,-0.5],+ [-0.5,0.5,-0.5],+ [-0.5,-0.5,-0.5],+ [0.5,-0.5,-0.5],+ [0.5,-0.5,0.5],+ [-0.5,-0.5,-0.5],+ [0.5,-0.5,0.5],+ [-0.5,-0.5,0.5],+ [-0.5,-0.5,0.5],+ [0.5,-0.5,0.5],+ [0.5,0.5,0.5],+ [-0.5,-0.5,0.5],+ [0.5,0.5,0.5],+ [-0.5,0.5,0.5],+ [0.5,-0.5,-0.5],+ [-0.5,-0.5,-0.5],+ [-0.5,0.5,-0.5],+ [0.5,-0.5,-0.5],+ [-0.5,0.5,-0.5],+ [0.5,0.5,-0.5]+ ]+ },+ "shape_box_uv0": {+ "type": "vec2",+ "data": [+ [0,1],+ [1,1],+ [1,0],+ [0,1],+ [1,0],+ [0,0],+ [0,1],+ [1,1],+ [1,0],+ [0,1],+ [1,0],+ [0,0],+ [0,1],+ [1,1],+ [1,0],+ [0,1],+ [1,0],+ [0,0],+ [0,1],+ [1,1],+ [1,0],+ [0,1],+ [1,0],+ [0,0],+ [0,1],+ [1,1],+ [1,0],+ [0,1],+ [1,0],+ [0,0],+ [0,1],+ [1,1],+ [1,0],+ [0,1],+ [1,0],+ [0,0]+ ]+ },+ "shape_sphere_indices": {+ "type": "u32",+ "file": "geometry.bin",+ "offset": 0,+ "count": 4416+ },+ "shape_sphere_normal": {+ "type": "vec3",+ "file": "geometry.bin",+ "offset": 17664,+ "count": 4416+ },+ "shape_sphere_position": {+ "type": "vec3",+ "file": "geometry.bin",+ "offset": 17664,+ "count": 4416+ },+ "shape_sphere_uv0": {+ "type": "vec2",+ "file": "geometry.bin",+ "offset": 70656,+ "count": 4416+ },+ "shape_plane_indices": {+ "type": "u32",+ "data": [0,1,2,3,4,5]+ },+ "shape_plane_normal": {+ "type": "vec3",+ "data": [+ [0,1,0],+ [0,1,0],+ [0,1,0],+ [0,1,0],+ [0,1,0],+ [0,1,0]+ ]+ },+ "shape_plane_position": {+ "type": "vec3",+ "data": [+ [-0.5,0,0.5],+ [0.5,0,0.5],+ [0.5,0,-0.5],+ [-0.5,0,0.5],+ [0.5,0,-0.5],+ [-0.5,0,-0.5]+ ]+ },+ "shape_plane_uv0": {+ "type": "vec2",+ "data": [+ [0,1],+ [1,1],+ [1,0],+ [0,1],+ [1,0],+ [0,0]+ ]+ }+ },+ "geometry": {+ "shape_box": {+ "attributes": {+ "NORMAL": "shape_box_normal",+ "POSITION": "shape_box_position",+ "TEXCOORD_0": "shape_box_uv0"+ },+ "indices": "shape_box_indices"+ },+ "shape_sphere": {+ "attributes": {+ "NORMAL": "shape_sphere_normal",+ "POSITION": "shape_sphere_position",+ "TEXCOORD_0": "shape_sphere_uv0"+ },+ "indices": "shape_sphere_indices"+ },+ "shape_plane": {+ "attributes": {+ "NORMAL": "shape_plane_normal",+ "POSITION": "shape_plane_position",+ "TEXCOORD_0": "shape_plane_uv0"+ },+ "indices": "shape_plane_indices"+ }+ },+ "animation": [+ {+ "tracks": [+ {+ "path": ["nodes","box","translation"],+ "keys": [[0,[-1,0,0]],[1,[0,0,0]]],+ "interpolation": "LINEAR"+ }+ ]+ }+ ]+}diff --git a/crates/vork-render/tests/fixtures/closed-glass-slab.json b/crates/vork-render/tests/fixtures/closed-glass-slab.jsonnew file mode 100644index 0000000..33b16ef--- /dev/null+++ b/crates/vork-render/tests/fixtures/closed-glass-slab.json@@ -0,0 +1 @@+{"version": 2, "buffers": {"unit-box_position": {"type": "vec3", "data": [[0.5, -0.5, 0.5], [0.5, -0.5, -0.5], [0.5, 0.5, 0.5], [0.5, 0.5, -0.5], [-0.5, -0.5, -0.5], [-0.5, -0.5, 0.5], [-0.5, 0.5, -0.5], [-0.5, 0.5, 0.5], [-0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [-0.5, 0.5, -0.5], [0.5, 0.5, -0.5], [-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, -0.5, 0.5], [0.5, -0.5, 0.5], [-0.5, -0.5, 0.5], [0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, -0.5, -0.5], [-0.5, -0.5, -0.5], [0.5, 0.5, -0.5], [-0.5, 0.5, -0.5]]}, "unit-box_normal": {"type": "vec3", "data": [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [-1, 0, 0], [-1, 0, 0], [-1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, -1, 0], [0, -1, 0], [0, -1, 0], [0, -1, 0], [0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, -1], [0, 0, -1], [0, 0, -1], [0, 0, -1]]}, "unit-box_uv0": {"type": "vec2", "data": [[0, 1], [1, 1], [0, 0], [1, 0], [0, 1], [1, 1], [0, 0], [1, 0], [0, 1], [1, 1], [0, 0], [1, 0], [0, 1], [1, 1], [0, 0], [1, 0], [0, 1], [1, 1], [0, 0], [1, 0], [0, 1], [1, 1], [0, 0], [1, 0]]}, "unit-box_indices": {"type": "u32", "data": [0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6, 8, 9, 11, 8, 11, 10, 12, 13, 15, 12, 15, 14, 16, 17, 19, 16, 19, 18, 20, 21, 23, 20, 23, 22]}}, "geometry": {"unit-box": {"topology": "triangles", "attributes": {"POSITION": "unit-box_position", "NORMAL": "unit-box_normal", "TEXCOORD_0": "unit-box_uv0"}, "indices": "unit-box_indices"}}, "materials": {"glass": {"inputs": {"transmission_weight": 1, "specular_roughness": 0, "specular_ior": 1.5}}, "emitter": {"inputs": {"base_weight": 0, "emission_color": [1, 1, 1], "emission_luminance": 1}}}, "nodes": [{"type":"camera","name":"camera","translation":[0,0,6],"material":{"program":"std/camera","inputs":{"projection":"ortho","ortho_scale":2}}}, {"type": "mesh", "name": "receiver", "geometry": "unit-box", "materials": ["emitter"], "translation": [0,0,-4], "scale": [30,30,0.1]}, {"type": "mesh", "name": "slab", "geometry": "unit-box", "materials": ["glass"], "scale": [10,10,0.5], "rotation": [0,0.19866933079506122,0,0.9800665778412416]}], "render": {"resolution": [64, 64], "display": {"program":"std/standard","inputs":{"dither_intensity":0}}}}diff --git a/crates/vork-render/tests/fixtures/emitter-knot.ies b/crates/vork-render/tests/fixtures/emitter-knot.iesnew file mode 100644index 0000000..64c27d2--- /dev/null+++ b/crates/vork-render/tests/fixtures/emitter-knot.ies@@ -0,0 +1,9 @@+IESNA:LM-63-2002+TILT=NONE+1 1000 1 7 4 1 1 0 0 0 1 1 10+0 20 20.01 20.02 60 90 180+0 90 180 360+0 0 100 0 0 0 0+0 0 200 0 0 0 0+0 0 400 0 0 0 0+0 0 100 0 0 0 0diff --git a/crates/vork-render/tests/fixtures/fibre-receiver.json b/crates/vork-render/tests/fixtures/fibre-receiver.jsonnew file mode 100644index 0000000..7ee26dd--- /dev/null+++ b/crates/vork-render/tests/fixtures/fibre-receiver.json@@ -0,0 +1,169 @@+{+ "version": 2,+ "buffers": {+ "p": {+ "type": "vec3",+ "data": [+ [+ 0,+ -0.8,+ 0+ ],+ [+ 0,+ 0.8,+ 0+ ]+ ]+ },+ "w": {+ "type": "f32",+ "data": [+ 0.4,+ 0.4+ ]+ },+ "c": {+ "type": "u32",+ "data": [+ 2+ ]+ },+ "q": {+ "type": "vec3",+ "data": [+ [+ -1.2,+ -1.2,+ -1+ ],+ [+ 1.2,+ -1.2,+ -1+ ],+ [+ 1.2,+ 1.2,+ -1+ ],+ [+ -1.2,+ 1.2,+ -1+ ]+ ]+ },+ "n": {+ "type": "vec3",+ "data": [+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ]+ ]+ },+ "i": {+ "type": "u32",+ "data": [+ 0,+ 1,+ 2,+ 0,+ 2,+ 3+ ]+ }+ },+ "geometry": {+ "strand": {+ "topology": "curves",+ "attributes": {+ "POSITION": "p"+ },+ "widths": "w",+ "curve_vertex_counts": "c"+ },+ "plane": {+ "attributes": {+ "POSITION": "q",+ "NORMAL": "n"+ },+ "indices": "i"+ }+ },+ "programs": {+ "test_hair": {+ "file": "hair-model.slang"+ }+ },+ "materials": {+ "hair": {+ "program": "test_hair",+ "inputs": {+ "color": [+ 0.5,+ 0.3,+ 0.1+ ],+ "model": "chiang"+ }+ },+ "white": {+ "inputs": {+ "base_color": [+ 0.8,+ 0.8,+ 0.8+ ],+ "specular_weight": 0+ }+ }+ },+ "nodes": [+ {"type":"camera","translation":[0,0,5],"material":{"program":"std/camera","inputs":{"projection":"ortho","ortho_scale":3}}},+ {+ "type": "mesh",+ "geometry": "plane",+ "materials": [+ "white"+ ]+ },+ {+ "type": "mesh",+ "geometry": "strand",+ "materials": [+ "hair"+ ],+ "visible_camera": false+ },+ {+ "type": "light",+ "shape": "sun",+ "energy": 2,+ "angle": 0+ }+ ],+ "render": {+ "resolution": [+ 64,+ 64+ ],+ "display": {"program":"std/standard","inputs":{"dither_intensity":0}}}+}diff --git a/crates/vork-render/tests/fixtures/hair-model.slang b/crates/vork-render/tests/fixtures/hair-model.slangnew file mode 100644index 0000000..061c97a--- /dev/null+++ b/crates/vork-render/tests/fixtures/hair-model.slang@@ -0,0 +1,16 @@+// Custom Hair program for testing diffuse and physical closure consumers.+import vork;+import std.hair_bsdf;+enum HairModel { Chiang, Diffuse };+struct Inputs {+ HairModel model = HairModel::Diffuse;+ float3 color = float3(0.017513,0.005763,0.002059);+ float roughness = 0.3;+ float offset = 0.034906585;+};+Hair surface(ShadingContext ctx, Inputs i) {+ var h = principled_hair(i.color,i.roughness,0.3,0.,1.55,i.offset);+ h.color=max(i.color,float3(0.));+ h.scattering = i.model == HairModel::Chiang;+ return h;+}diff --git a/crates/vork-render/tests/fixtures/hit-layers.json b/crates/vork-render/tests/fixtures/hit-layers.jsonnew file mode 100644index 0000000..4906d6d--- /dev/null+++ b/crates/vork-render/tests/fixtures/hit-layers.json@@ -0,0 +1 @@+{"version":2,"buffers":{"p":{"type":"vec3","data":[[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.19509032201612825,0.9807852804032304,0.0],[0.19134171618254486,0.9807852804032304,0.03806023374435662],[0.18023995550173696,0.9807852804032304,0.0746578340503426],[0.16221167441072887,0.9807852804032304,0.1083863756623696],[0.1379496896414715,0.9807852804032304,0.13794968964147147],[0.10838637566236961,0.9807852804032304,0.16221167441072887],[0.07465783405034261,0.9807852804032304,0.18023995550173696],[0.03806023374435663,0.9807852804032304,0.19134171618254486],[1.1945836920083893e-17,0.9807852804032304,0.19509032201612825],[-0.0380602337443566,0.9807852804032304,0.19134171618254486],[-0.07465783405034258,0.9807852804032304,0.18023995550173696],[-0.10838637566236956,0.9807852804032304,0.1622116744107289],[-0.13794968964147147,0.9807852804032304,0.1379496896414715],[-0.16221167441072887,0.9807852804032304,0.1083863756623696],[-0.18023995550173696,0.9807852804032304,0.07465783405034263],[-0.19134171618254486,0.9807852804032304,0.038060233744356686],[-0.19509032201612825,0.9807852804032304,2.3891673840167787e-17],[-0.19134171618254486,0.9807852804032304,-0.03806023374435664],[-0.18023995550173696,0.9807852804032304,-0.07465783405034258],[-0.1622116744107289,0.9807852804032304,-0.10838637566236956],[-0.13794968964147153,0.9807852804032304,-0.13794968964147147],[-0.1083863756623696,0.9807852804032304,-0.16221167441072887],[-0.07465783405034271,0.9807852804032304,-0.1802399555017369],[-0.03806023374435669,0.9807852804032304,-0.19134171618254484],[-3.583751076025168e-17,0.9807852804032304,-0.19509032201612825],[0.038060233744356624,0.9807852804032304,-0.19134171618254486],[0.07465783405034264,0.9807852804032304,-0.18023995550173694],[0.10838637566236953,0.9807852804032304,-0.1622116744107289],[0.13794968964147145,0.9807852804032304,-0.13794968964147153],[0.16221167441072887,0.9807852804032304,-0.1083863756623696],[0.1802399555017369,0.9807852804032304,-0.07465783405034272],[0.19134171618254484,0.9807852804032304,-0.03806023374435671],[0.19509032201612825,0.9807852804032304,-4.7783347680335573e-17],[0.3826834323650898,0.9238795325112867,0.0],[0.37533027751786524,0.9238795325112867,0.0746578340503426],[0.3535533905932738,0.9238795325112867,0.14644660940672624],[0.31818964514320847,0.9238795325112867,0.2126075236918141],[0.2705980500730985,0.9238795325112867,0.27059805007309845],[0.21260752369181415,0.9238795325112867,0.31818964514320847],[0.14644660940672627,0.9238795325112867,0.3535533905932738],[0.07465783405034264,0.9238795325112867,0.37533027751786524],[2.3432602026631493e-17,0.9238795325112867,0.3826834323650898],[-0.07465783405034258,0.9238795325112867,0.37533027751786524],[-0.1464466094067262,0.9238795325112867,0.3535533905932738],[-0.21260752369181402,0.9238795325112867,0.3181896451432086],[-0.27059805007309845,0.9238795325112867,0.2705980500730985],[-0.3181896451432085,0.9238795325112867,0.2126075236918141],[-0.3535533905932738,0.9238795325112867,0.1464466094067263],[-0.37533027751786524,0.9238795325112867,0.07465783405034274],[-0.3826834323650898,0.9238795325112867,4.6865204053262986e-17],[-0.37533027751786524,0.9238795325112867,-0.07465783405034264],[-0.3535533905932738,0.9238795325112867,-0.1464466094067262],[-0.3181896451432086,0.9238795325112867,-0.21260752369181402],[-0.27059805007309856,0.9238795325112867,-0.27059805007309845],[-0.2126075236918141,0.9238795325112867,-0.31818964514320847],[-0.14644660940672646,0.9238795325112867,-0.3535533905932737],[-0.07465783405034276,0.9238795325112867,-0.3753302775178652],[-7.029780607989448e-17,0.9238795325112867,-0.3826834323650898],[0.07465783405034263,0.9238795325112867,-0.37533027751786524],[0.14644660940672632,0.9238795325112867,-0.35355339059327373],[0.21260752369181396,0.9238795325112867,-0.3181896451432086],[0.27059805007309845,0.9238795325112867,-0.27059805007309856],[0.31818964514320847,0.9238795325112867,-0.2126075236918141],[0.3535533905932737,0.9238795325112867,-0.1464466094067265],[0.3753302775178652,0.9238795325112867,-0.07465783405034278],[0.3826834323650898,0.9238795325112867,-9.373040810652597e-17],[0.5555702330196022,0.8314696123025452,0.0],[0.5448951067758185,0.8314696123025452,0.1083863756623696],[0.5132799671593367,0.8314696123025452,0.2126075236918141],[0.4619397662556433,0.8314696123025452,0.3086582838174551],[0.39284747919355106,0.8314696123025452,0.392847479193551],[0.30865828381745514,0.8314696123025452,0.4619397662556433],[0.21260752369181413,0.8314696123025452,0.5132799671593367],[0.10838637566236964,0.8314696123025452,0.5448951067758185],[3.401886537845025e-17,0.8314696123025452,0.5555702330196022],[-0.10838637566236957,0.8314696123025452,0.5448951067758185],[-0.21260752369181407,0.8314696123025452,0.5132799671593367],[-0.3086582838174549,0.8314696123025452,0.4619397662556435],[-0.392847479193551,0.8314696123025452,0.39284747919355106],[-0.4619397662556434,0.8314696123025452,0.3086582838174551],[-0.5132799671593367,0.8314696123025452,0.21260752369181415],[-0.5448951067758185,0.8314696123025452,0.10838637566236979],[-0.5555702330196022,0.8314696123025452,6.80377307569005e-17],[-0.5448951067758185,0.8314696123025452,-0.10838637566236965],[-0.5132799671593368,0.8314696123025452,-0.21260752369181404],[-0.4619397662556435,0.8314696123025452,-0.3086582838174549],[-0.3928474791935511,0.8314696123025452,-0.392847479193551],[-0.3086582838174551,0.8314696123025452,-0.4619397662556433],[-0.2126075236918144,0.8314696123025452,-0.5132799671593365],[-0.10838637566236983,0.8314696123025452,-0.5448951067758185],[-1.0205659613535074e-16,0.8314696123025452,-0.5555702330196022],[0.10838637566236962,0.8314696123025452,-0.5448951067758185],[0.2126075236918142,0.8314696123025452,-0.5132799671593367],[0.30865828381745486,0.8314696123025452,-0.4619397662556435],[0.39284747919355095,0.8314696123025452,-0.3928474791935511],[0.4619397662556433,0.8314696123025452,-0.3086582838174551],[0.5132799671593365,0.8314696123025452,-0.21260752369181443],[0.5448951067758185,0.8314696123025452,-0.10838637566236986],[0.5555702330196022,0.8314696123025452,-1.36075461513801e-16],[0.7071067811865475,0.7071067811865476,0.0],[0.6935199226610737,0.7071067811865476,0.13794968964147147],[0.6532814824381882,0.7071067811865476,0.27059805007309845],[0.5879378012096793,0.7071067811865476,0.392847479193551],[0.5,0.7071067811865476,0.4999999999999999],[0.3928474791935511,0.7071067811865476,0.5879378012096793],[0.2705980500730985,0.7071067811865476,0.6532814824381882],[0.13794968964147153,0.7071067811865476,0.6935199226610737],[4.329780281177466e-17,0.7071067811865476,0.7071067811865475],[-0.13794968964147145,0.7071067811865476,0.6935199226610737],[-0.27059805007309845,0.7071067811865476,0.6532814824381882],[-0.39284747919355084,0.7071067811865476,0.5879378012096794],[-0.4999999999999999,0.7071067811865476,0.5],[-0.5879378012096794,0.7071067811865476,0.392847479193551],[-0.6532814824381882,0.7071067811865476,0.27059805007309856],[-0.6935199226610737,0.7071067811865476,0.13794968964147172],[-0.7071067811865475,0.7071067811865476,8.659560562354932e-17],[-0.6935199226610737,0.7071067811865476,-0.13794968964147156],[-0.6532814824381883,0.7071067811865476,-0.2705980500730984],[-0.5879378012096794,0.7071067811865476,-0.39284747919355084],[-0.5000000000000001,0.7071067811865476,-0.4999999999999999],[-0.392847479193551,0.7071067811865476,-0.5879378012096793],[-0.2705980500730989,0.7071067811865476,-0.6532814824381881],[-0.13794968964147178,0.7071067811865476,-0.6935199226610735],[-1.2989340843532398e-16,0.7071067811865476,-0.7071067811865475],[0.13794968964147153,0.7071067811865476,-0.6935199226610737],[0.2705980500730986,0.7071067811865476,-0.6532814824381881],[0.3928474791935508,0.7071067811865476,-0.5879378012096794],[0.49999999999999983,0.7071067811865476,-0.5000000000000001],[0.5879378012096793,0.7071067811865476,-0.392847479193551],[0.6532814824381881,0.7071067811865476,-0.2705980500730989],[0.6935199226610735,0.7071067811865476,-0.1379496896414718],[0.7071067811865475,0.7071067811865476,-1.7319121124709863e-16],[0.8314696123025452,0.5555702330196023,0.0],[0.8154931568489171,0.5555702330196023,0.16221167441072887],[0.7681777567114163,0.5555702330196023,0.31818964514320847],[0.6913417161825449,0.5555702330196023,0.4619397662556433],[0.5879378012096794,0.5555702330196023,0.5879378012096793],[0.4619397662556434,0.5555702330196023,0.6913417161825449],[0.3181896451432085,0.5555702330196023,0.7681777567114163],[0.16221167441072892,0.5555702330196023,0.8154931568489171],[5.091282996473014e-17,0.5555702330196023,0.8314696123025452],[-0.1622116744107288,0.5555702330196023,0.8154931568489171],[-0.31818964514320847,0.5555702330196023,0.7681777567114163],[-0.46193976625564315,0.5555702330196023,0.691341716182545],[-0.5879378012096793,0.5555702330196023,0.5879378012096794],[-0.691341716182545,0.5555702330196023,0.4619397662556433],[-0.7681777567114163,0.5555702330196023,0.3181896451432086],[-0.8154931568489171,0.5555702330196023,0.16221167441072917],[-0.8314696123025452,0.5555702330196023,1.0182565992946028e-16],[-0.8154931568489171,0.5555702330196023,-0.16221167441072895],[-0.7681777567114164,0.5555702330196023,-0.3181896451432084],[-0.691341716182545,0.5555702330196023,-0.46193976625564315],[-0.5879378012096795,0.5555702330196023,-0.5879378012096793],[-0.4619397662556433,0.5555702330196023,-0.6913417161825449],[-0.31818964514320897,0.5555702330196023,-0.7681777567114161],[-0.1622116744107292,0.5555702330196023,-0.815493156848917],[-1.527384898941904e-16,0.5555702330196023,-0.8314696123025452],[0.1622116744107289,0.5555702330196023,-0.8154931568489171],[0.3181896451432087,0.5555702330196023,-0.7681777567114162],[0.46193976625564304,0.5555702330196023,-0.691341716182545],[0.5879378012096792,0.5555702330196023,-0.5879378012096795],[0.6913417161825449,0.5555702330196023,-0.4619397662556433],[0.7681777567114161,0.5555702330196023,-0.318189645143209],[0.815493156848917,0.5555702330196023,-0.16221167441072926],[0.8314696123025452,0.5555702330196023,-2.0365131985892056e-16],[0.9238795325112867,0.38268343236508984,0.0],[0.9061274463528878,0.38268343236508984,0.18023995550173696],[0.8535533905932737,0.38268343236508984,0.3535533905932738],[0.7681777567114163,0.38268343236508984,0.5132799671593367],[0.6532814824381883,0.38268343236508984,0.6532814824381882],[0.5132799671593368,0.38268343236508984,0.7681777567114163],[0.35355339059327384,0.38268343236508984,0.8535533905932737],[0.18023995550173702,0.38268343236508984,0.9061274463528878],[5.657130561438501e-17,0.38268343236508984,0.9238795325112867],[-0.1802399555017369,0.38268343236508984,0.9061274463528878],[-0.35355339059327373,0.38268343236508984,0.8535533905932737],[-0.5132799671593365,0.38268343236508984,0.7681777567114165],[-0.6532814824381882,0.38268343236508984,0.6532814824381883],[-0.7681777567114164,0.38268343236508984,0.5132799671593367],[-0.8535533905932737,0.38268343236508984,0.35355339059327384],[-0.9061274463528878,0.38268343236508984,0.1802399555017373],[-0.9238795325112867,0.38268343236508984,1.1314261122877003e-16],[-0.9061274463528878,0.38268343236508984,-0.18023995550173705],[-0.8535533905932738,0.38268343236508984,-0.3535533905932737],[-0.7681777567114165,0.38268343236508984,-0.5132799671593365],[-0.6532814824381884,0.38268343236508984,-0.6532814824381882],[-0.5132799671593367,0.38268343236508984,-0.7681777567114163],[-0.3535533905932743,0.38268343236508984,-0.8535533905932735],[-0.18023995550173735,0.38268343236508984,-0.9061274463528877],[-1.6971391684315505e-16,0.38268343236508984,-0.9238795325112867],[0.18023995550173702,0.38268343236508984,-0.9061274463528878],[0.35355339059327395,0.38268343236508984,-0.8535533905932736],[0.5132799671593364,0.38268343236508984,-0.7681777567114165],[0.6532814824381881,0.38268343236508984,-0.6532814824381884],[0.7681777567114163,0.38268343236508984,-0.5132799671593367],[0.8535533905932735,0.38268343236508984,-0.35355339059327434],[0.9061274463528877,0.38268343236508984,-0.18023995550173738],[0.9238795325112867,0.38268343236508984,-2.2628522245754005e-16],[0.9807852804032304,0.19509032201612833,0.0],[0.9619397662556434,0.19509032201612833,0.19134171618254486],[0.9061274463528878,0.19509032201612833,0.37533027751786524],[0.8154931568489171,0.19509032201612833,0.5448951067758185],[0.6935199226610738,0.19509032201612833,0.6935199226610737],[0.5448951067758186,0.19509032201612833,0.8154931568489171],[0.3753302775178653,0.19509032201612833,0.9061274463528878],[0.19134171618254495,0.19509032201612833,0.9619397662556434],[6.005577771483278e-17,0.19509032201612833,0.9807852804032304],[-0.1913417161825448,0.19509032201612833,0.9619397662556434],[-0.3753302775178652,0.19509032201612833,0.9061274463528878],[-0.5448951067758184,0.19509032201612833,0.8154931568489173],[-0.6935199226610737,0.19509032201612833,0.6935199226610738],[-0.8154931568489172,0.19509032201612833,0.5448951067758185],[-0.9061274463528878,0.19509032201612833,0.37533027751786535],[-0.9619397662556434,0.19509032201612833,0.19134171618254522],[-0.9807852804032304,0.19509032201612833,1.2011155542966555e-16],[-0.9619397662556434,0.19509032201612833,-0.19134171618254497],[-0.9061274463528879,0.19509032201612833,-0.37533027751786513],[-0.8154931568489173,0.19509032201612833,-0.5448951067758184],[-0.6935199226610739,0.19509032201612833,-0.6935199226610737],[-0.5448951067758185,0.19509032201612833,-0.8154931568489171],[-0.3753302775178658,0.19509032201612833,-0.9061274463528876],[-0.19134171618254528,0.19509032201612833,-0.9619397662556433],[-1.8016733314449831e-16,0.19509032201612833,-0.9807852804032304],[0.19134171618254492,0.19509032201612833,-0.9619397662556434],[0.37533027751786546,0.19509032201612833,-0.9061274463528877],[0.5448951067758183,0.19509032201612833,-0.8154931568489173],[0.6935199226610735,0.19509032201612833,-0.6935199226610739],[0.8154931568489171,0.19509032201612833,-0.5448951067758185],[0.9061274463528876,0.19509032201612833,-0.37533027751786585],[0.9619397662556433,0.19509032201612833,-0.19134171618254533],[0.9807852804032304,0.19509032201612833,-2.402231108593311e-16],[1.0,6.123233995736766e-17,0.0],[0.9807852804032304,6.123233995736766e-17,0.19509032201612825],[0.9238795325112867,6.123233995736766e-17,0.3826834323650898],[0.8314696123025452,6.123233995736766e-17,0.5555702330196022],[0.7071067811865476,6.123233995736766e-17,0.7071067811865475],[0.5555702330196023,6.123233995736766e-17,0.8314696123025452],[0.38268343236508984,6.123233995736766e-17,0.9238795325112867],[0.19509032201612833,6.123233995736766e-17,0.9807852804032304],[6.123233995736766e-17,6.123233995736766e-17,1.0],[-0.1950903220161282,6.123233995736766e-17,0.9807852804032304],[-0.3826834323650897,6.123233995736766e-17,0.9238795325112867],[-0.555570233019602,6.123233995736766e-17,0.8314696123025455],[-0.7071067811865475,6.123233995736766e-17,0.7071067811865476],[-0.8314696123025453,6.123233995736766e-17,0.5555702330196022],[-0.9238795325112867,6.123233995736766e-17,0.3826834323650899],[-0.9807852804032304,6.123233995736766e-17,0.1950903220161286],[-1.0,6.123233995736766e-17,1.2246467991473532e-16],[-0.9807852804032304,6.123233995736766e-17,-0.19509032201612836],[-0.9238795325112868,6.123233995736766e-17,-0.38268343236508967],[-0.8314696123025455,6.123233995736766e-17,-0.555570233019602],[-0.7071067811865477,6.123233995736766e-17,-0.7071067811865475],[-0.5555702330196022,6.123233995736766e-17,-0.8314696123025452],[-0.38268343236509034,6.123233995736766e-17,-0.9238795325112865],[-0.19509032201612866,6.123233995736766e-17,-0.9807852804032303],[-1.8369701987210297e-16,6.123233995736766e-17,-1.0],[0.1950903220161283,6.123233995736766e-17,-0.9807852804032304],[0.38268343236509,6.123233995736766e-17,-0.9238795325112866],[0.5555702330196018,6.123233995736766e-17,-0.8314696123025455],[0.7071067811865474,6.123233995736766e-17,-0.7071067811865477],[0.8314696123025452,6.123233995736766e-17,-0.5555702330196022],[0.9238795325112865,6.123233995736766e-17,-0.3826834323650904],[0.9807852804032303,6.123233995736766e-17,-0.19509032201612872],[1.0,6.123233995736766e-17,-2.4492935982947064e-16],[0.9807852804032304,-0.1950903220161282,0.0],[0.9619397662556434,-0.1950903220161282,0.19134171618254486],[0.9061274463528878,-0.1950903220161282,0.37533027751786524],[0.8154931568489171,-0.1950903220161282,0.5448951067758185],[0.6935199226610738,-0.1950903220161282,0.6935199226610737],[0.5448951067758186,-0.1950903220161282,0.8154931568489171],[0.3753302775178653,-0.1950903220161282,0.9061274463528878],[0.19134171618254495,-0.1950903220161282,0.9619397662556434],[6.005577771483278e-17,-0.1950903220161282,0.9807852804032304],[-0.1913417161825448,-0.1950903220161282,0.9619397662556434],[-0.3753302775178652,-0.1950903220161282,0.9061274463528878],[-0.5448951067758184,-0.1950903220161282,0.8154931568489173],[-0.6935199226610737,-0.1950903220161282,0.6935199226610738],[-0.8154931568489172,-0.1950903220161282,0.5448951067758185],[-0.9061274463528878,-0.1950903220161282,0.37533027751786535],[-0.9619397662556434,-0.1950903220161282,0.19134171618254522],[-0.9807852804032304,-0.1950903220161282,1.2011155542966555e-16],[-0.9619397662556434,-0.1950903220161282,-0.19134171618254497],[-0.9061274463528879,-0.1950903220161282,-0.37533027751786513],[-0.8154931568489173,-0.1950903220161282,-0.5448951067758184],[-0.6935199226610739,-0.1950903220161282,-0.6935199226610737],[-0.5448951067758185,-0.1950903220161282,-0.8154931568489171],[-0.3753302775178658,-0.1950903220161282,-0.9061274463528876],[-0.19134171618254528,-0.1950903220161282,-0.9619397662556433],[-1.8016733314449831e-16,-0.1950903220161282,-0.9807852804032304],[0.19134171618254492,-0.1950903220161282,-0.9619397662556434],[0.37533027751786546,-0.1950903220161282,-0.9061274463528877],[0.5448951067758183,-0.1950903220161282,-0.8154931568489173],[0.6935199226610735,-0.1950903220161282,-0.6935199226610739],[0.8154931568489171,-0.1950903220161282,-0.5448951067758185],[0.9061274463528876,-0.1950903220161282,-0.37533027751786585],[0.9619397662556433,-0.1950903220161282,-0.19134171618254533],[0.9807852804032304,-0.1950903220161282,-2.402231108593311e-16],[0.9238795325112867,-0.3826834323650897,0.0],[0.9061274463528878,-0.3826834323650897,0.18023995550173696],[0.8535533905932737,-0.3826834323650897,0.3535533905932738],[0.7681777567114163,-0.3826834323650897,0.5132799671593367],[0.6532814824381883,-0.3826834323650897,0.6532814824381882],[0.5132799671593368,-0.3826834323650897,0.7681777567114163],[0.35355339059327384,-0.3826834323650897,0.8535533905932737],[0.18023995550173702,-0.3826834323650897,0.9061274463528878],[5.657130561438501e-17,-0.3826834323650897,0.9238795325112867],[-0.1802399555017369,-0.3826834323650897,0.9061274463528878],[-0.35355339059327373,-0.3826834323650897,0.8535533905932737],[-0.5132799671593365,-0.3826834323650897,0.7681777567114165],[-0.6532814824381882,-0.3826834323650897,0.6532814824381883],[-0.7681777567114164,-0.3826834323650897,0.5132799671593367],[-0.8535533905932737,-0.3826834323650897,0.35355339059327384],[-0.9061274463528878,-0.3826834323650897,0.1802399555017373],[-0.9238795325112867,-0.3826834323650897,1.1314261122877003e-16],[-0.9061274463528878,-0.3826834323650897,-0.18023995550173705],[-0.8535533905932738,-0.3826834323650897,-0.3535533905932737],[-0.7681777567114165,-0.3826834323650897,-0.5132799671593365],[-0.6532814824381884,-0.3826834323650897,-0.6532814824381882],[-0.5132799671593367,-0.3826834323650897,-0.7681777567114163],[-0.3535533905932743,-0.3826834323650897,-0.8535533905932735],[-0.18023995550173735,-0.3826834323650897,-0.9061274463528877],[-1.6971391684315505e-16,-0.3826834323650897,-0.9238795325112867],[0.18023995550173702,-0.3826834323650897,-0.9061274463528878],[0.35355339059327395,-0.3826834323650897,-0.8535533905932736],[0.5132799671593364,-0.3826834323650897,-0.7681777567114165],[0.6532814824381881,-0.3826834323650897,-0.6532814824381884],[0.7681777567114163,-0.3826834323650897,-0.5132799671593367],[0.8535533905932735,-0.3826834323650897,-0.35355339059327434],[0.9061274463528877,-0.3826834323650897,-0.18023995550173738],[0.9238795325112867,-0.3826834323650897,-2.2628522245754005e-16],[0.8314696123025455,-0.555570233019602,0.0],[0.8154931568489173,-0.555570233019602,0.1622116744107289],[0.7681777567114165,-0.555570233019602,0.3181896451432086],[0.691341716182545,-0.555570233019602,0.4619397662556435],[0.5879378012096795,-0.555570233019602,0.5879378012096794],[0.46193976625564354,-0.555570233019602,0.691341716182545],[0.31818964514320863,-0.555570233019602,0.7681777567114165],[0.16221167441072898,-0.555570233019602,0.8154931568489173],[5.091282996473015e-17,-0.555570233019602,0.8314696123025455],[-0.16221167441072887,-0.555570233019602,0.8154931568489173],[-0.3181896451432085,-0.555570233019602,0.7681777567114165],[-0.46193976625564326,-0.555570233019602,0.6913417161825453],[-0.5879378012096794,-0.555570233019602,0.5879378012096795],[-0.6913417161825451,-0.555570233019602,0.4619397662556435],[-0.7681777567114165,-0.555570233019602,0.3181896451432087],[-0.8154931568489173,-0.555570233019602,0.1622116744107292],[-0.8314696123025455,-0.555570233019602,1.018256599294603e-16],[-0.8154931568489173,-0.555570233019602,-0.162211674410729],[-0.7681777567114166,-0.555570233019602,-0.31818964514320847],[-0.6913417161825453,-0.555570233019602,-0.46193976625564326],[-0.5879378012096796,-0.555570233019602,-0.5879378012096794],[-0.4619397662556435,-0.555570233019602,-0.691341716182545],[-0.318189645143209,-0.555570233019602,-0.7681777567114163],[-0.16221167441072926,-0.555570233019602,-0.8154931568489172],[-1.5273848989419045e-16,-0.555570233019602,-0.8314696123025455],[0.16221167441072895,-0.555570233019602,-0.8154931568489173],[0.31818964514320874,-0.555570233019602,-0.7681777567114164],[0.4619397662556432,-0.555570233019602,-0.6913417161825453],[0.5879378012096794,-0.555570233019602,-0.5879378012096796],[0.691341716182545,-0.555570233019602,-0.4619397662556435],[0.7681777567114163,-0.555570233019602,-0.3181896451432091],[0.8154931568489172,-0.555570233019602,-0.16221167441072928],[0.8314696123025455,-0.555570233019602,-2.036513198589206e-16],[0.7071067811865476,-0.7071067811865475,0.0],[0.6935199226610738,-0.7071067811865475,0.1379496896414715],[0.6532814824381883,-0.7071067811865475,0.2705980500730985],[0.5879378012096794,-0.7071067811865475,0.39284747919355106],[0.5000000000000001,-0.7071067811865475,0.5],[0.3928474791935512,-0.7071067811865475,0.5879378012096794],[0.27059805007309856,-0.7071067811865475,0.6532814824381883],[0.13794968964147156,-0.7071067811865475,0.6935199226610738],[4.329780281177467e-17,-0.7071067811865475,0.7071067811865476],[-0.13794968964147147,-0.7071067811865475,0.6935199226610738],[-0.2705980500730985,-0.7071067811865475,0.6532814824381883],[-0.39284747919355095,-0.7071067811865475,0.5879378012096795],[-0.5,-0.7071067811865475,0.5000000000000001],[-0.5879378012096794,-0.7071067811865475,0.39284747919355106],[-0.6532814824381883,-0.7071067811865475,0.2705980500730986],[-0.6935199226610738,-0.7071067811865475,0.13794968964147175],[-0.7071067811865476,-0.7071067811865475,8.659560562354934e-17],[-0.6935199226610738,-0.7071067811865475,-0.13794968964147158],[-0.6532814824381884,-0.7071067811865475,-0.27059805007309845],[-0.5879378012096795,-0.7071067811865475,-0.39284747919355095],[-0.5000000000000001,-0.7071067811865475,-0.5],[-0.39284747919355106,-0.7071067811865475,-0.5879378012096794],[-0.2705980500730989,-0.7071067811865475,-0.6532814824381882],[-0.1379496896414718,-0.7071067811865475,-0.6935199226610737],[-1.29893408435324e-16,-0.7071067811865475,-0.7071067811865476],[0.13794968964147153,-0.7071067811865475,-0.6935199226610738],[0.2705980500730987,-0.7071067811865475,-0.6532814824381882],[0.39284747919355084,-0.7071067811865475,-0.5879378012096795],[0.4999999999999999,-0.7071067811865475,-0.5000000000000001],[0.5879378012096794,-0.7071067811865475,-0.39284747919355106],[0.6532814824381882,-0.7071067811865475,-0.27059805007309895],[0.6935199226610737,-0.7071067811865475,-0.13794968964147183],[0.7071067811865476,-0.7071067811865475,-1.7319121124709868e-16],[0.5555702330196022,-0.8314696123025453,0.0],[0.5448951067758185,-0.8314696123025453,0.1083863756623696],[0.5132799671593367,-0.8314696123025453,0.2126075236918141],[0.4619397662556433,-0.8314696123025453,0.3086582838174551],[0.39284747919355106,-0.8314696123025453,0.392847479193551],[0.30865828381745514,-0.8314696123025453,0.4619397662556433],[0.21260752369181413,-0.8314696123025453,0.5132799671593367],[0.10838637566236964,-0.8314696123025453,0.5448951067758185],[3.401886537845025e-17,-0.8314696123025453,0.5555702330196022],[-0.10838637566236957,-0.8314696123025453,0.5448951067758185],[-0.21260752369181407,-0.8314696123025453,0.5132799671593367],[-0.3086582838174549,-0.8314696123025453,0.4619397662556435],[-0.392847479193551,-0.8314696123025453,0.39284747919355106],[-0.4619397662556434,-0.8314696123025453,0.3086582838174551],[-0.5132799671593367,-0.8314696123025453,0.21260752369181415],[-0.5448951067758185,-0.8314696123025453,0.10838637566236979],[-0.5555702330196022,-0.8314696123025453,6.80377307569005e-17],[-0.5448951067758185,-0.8314696123025453,-0.10838637566236965],[-0.5132799671593368,-0.8314696123025453,-0.21260752369181404],[-0.4619397662556435,-0.8314696123025453,-0.3086582838174549],[-0.3928474791935511,-0.8314696123025453,-0.392847479193551],[-0.3086582838174551,-0.8314696123025453,-0.4619397662556433],[-0.2126075236918144,-0.8314696123025453,-0.5132799671593365],[-0.10838637566236983,-0.8314696123025453,-0.5448951067758185],[-1.0205659613535074e-16,-0.8314696123025453,-0.5555702330196022],[0.10838637566236962,-0.8314696123025453,-0.5448951067758185],[0.2126075236918142,-0.8314696123025453,-0.5132799671593367],[0.30865828381745486,-0.8314696123025453,-0.4619397662556435],[0.39284747919355095,-0.8314696123025453,-0.3928474791935511],[0.4619397662556433,-0.8314696123025453,-0.3086582838174551],[0.5132799671593365,-0.8314696123025453,-0.21260752369181443],[0.5448951067758185,-0.8314696123025453,-0.10838637566236986],[0.5555702330196022,-0.8314696123025453,-1.36075461513801e-16],[0.3826834323650899,-0.9238795325112867,0.0],[0.37533027751786535,-0.9238795325112867,0.07465783405034263],[0.35355339059327384,-0.9238795325112867,0.1464466094067263],[0.3181896451432086,-0.9238795325112867,0.21260752369181415],[0.2705980500730986,-0.9238795325112867,0.27059805007309856],[0.2126075236918142,-0.9238795325112867,0.3181896451432086],[0.1464466094067263,-0.9238795325112867,0.35355339059327384],[0.07465783405034265,-0.9238795325112867,0.37533027751786535],[2.34326020266315e-17,-0.9238795325112867,0.3826834323650899],[-0.0746578340503426,-0.9238795325112867,0.37533027751786535],[-0.14644660940672627,-0.9238795325112867,0.35355339059327384],[-0.21260752369181407,-0.9238795325112867,0.3181896451432087],[-0.27059805007309856,-0.9238795325112867,0.2705980500730986],[-0.31818964514320863,-0.9238795325112867,0.21260752369181415],[-0.35355339059327384,-0.9238795325112867,0.14644660940672632],[-0.37533027751786535,-0.9238795325112867,0.07465783405034276],[-0.3826834323650899,-0.9238795325112867,4.6865204053263e-17],[-0.37533027751786535,-0.9238795325112867,-0.07465783405034267],[-0.3535533905932739,-0.9238795325112867,-0.14644660940672624],[-0.3181896451432087,-0.9238795325112867,-0.21260752369181407],[-0.2705980500730986,-0.9238795325112867,-0.27059805007309856],[-0.21260752369181415,-0.9238795325112867,-0.3181896451432086],[-0.1464466094067265,-0.9238795325112867,-0.3535533905932738],[-0.07465783405034278,-0.9238795325112867,-0.3753302775178653],[-7.029780607989449e-17,-0.9238795325112867,-0.3826834323650899],[0.07465783405034264,-0.9238795325112867,-0.37533027751786535],[0.14644660940672638,-0.9238795325112867,-0.35355339059327384],[0.21260752369181404,-0.9238795325112867,-0.3181896451432087],[0.2705980500730985,-0.9238795325112867,-0.2705980500730986],[0.3181896451432086,-0.9238795325112867,-0.21260752369181415],[0.3535533905932738,-0.9238795325112867,-0.14644660940672652],[0.3753302775178653,-0.9238795325112867,-0.0746578340503428],[0.3826834323650899,-0.9238795325112867,-9.3730408106526e-17],[0.1950903220161286,-0.9807852804032304,0.0],[0.19134171618254522,-0.9807852804032304,0.038060233744356686],[0.1802399555017373,-0.9807852804032304,0.07465783405034274],[0.16221167441072917,-0.9807852804032304,0.10838637566236979],[0.13794968964147175,-0.9807852804032304,0.13794968964147172],[0.10838637566236982,-0.9807852804032304,0.16221167441072917],[0.07465783405034275,-0.9807852804032304,0.1802399555017373],[0.0380602337443567,-0.9807852804032304,0.19134171618254522],[1.1945836920083915e-17,-0.9807852804032304,0.1950903220161286],[-0.03806023374435667,-0.9807852804032304,0.19134171618254522],[-0.07465783405034272,-0.9807852804032304,0.1802399555017373],[-0.10838637566236975,-0.9807852804032304,0.1622116744107292],[-0.13794968964147172,-0.9807852804032304,0.13794968964147175],[-0.16221167441072917,-0.9807852804032304,0.10838637566236979],[-0.1802399555017373,-0.9807852804032304,0.07465783405034276],[-0.19134171618254522,-0.9807852804032304,0.038060233744356756],[-0.1950903220161286,-0.9807852804032304,2.389167384016783e-17],[-0.19134171618254522,-0.9807852804032304,-0.03806023374435671],[-0.18023995550173733,-0.9807852804032304,-0.07465783405034272],[-0.1622116744107292,-0.9807852804032304,-0.10838637566236975],[-0.13794968964147178,-0.9807852804032304,-0.13794968964147172],[-0.10838637566236979,-0.9807852804032304,-0.16221167441072917],[-0.07465783405034285,-0.9807852804032304,-0.18023995550173724],[-0.03806023374435676,-0.9807852804032304,-0.1913417161825452],[-3.583751076025174e-17,-0.9807852804032304,-0.1950903220161286],[0.03806023374435669,-0.9807852804032304,-0.19134171618254522],[0.07465783405034278,-0.9807852804032304,-0.18023995550173727],[0.10838637566236974,-0.9807852804032304,-0.1622116744107292],[0.13794968964147172,-0.9807852804032304,-0.13794968964147178],[0.16221167441072917,-0.9807852804032304,-0.10838637566236979],[0.18023995550173724,-0.9807852804032304,-0.07465783405034286],[0.1913417161825452,-0.9807852804032304,-0.038060233744356776],[0.1950903220161286,-0.9807852804032304,-4.778334768033566e-17],[1.2246467991473532e-16,-1.0,0.0],[1.2011155542966555e-16,-1.0,2.3891673840167787e-17],[1.1314261122877003e-16,-1.0,4.6865204053262986e-17],[1.0182565992946028e-16,-1.0,6.80377307569005e-17],[8.659560562354934e-17,-1.0,8.659560562354932e-17],[6.803773075690051e-17,-1.0,1.0182565992946028e-16],[4.686520405326299e-17,-1.0,1.1314261122877003e-16],[2.3891673840167796e-17,-1.0,1.2011155542966555e-16],[7.498798913309288e-33,-1.0,1.2246467991473532e-16],[-2.389167384016778e-17,-1.0,1.2011155542966555e-16],[-4.6865204053262974e-17,-1.0,1.1314261122877003e-16],[-6.803773075690047e-17,-1.0,1.018256599294603e-16],[-8.659560562354932e-17,-1.0,8.659560562354934e-17],[-1.0182565992946029e-16,-1.0,6.80377307569005e-17],[-1.1314261122877003e-16,-1.0,4.6865204053263e-17],[-1.2011155542966555e-16,-1.0,2.389167384016783e-17],[-1.2246467991473532e-16,-1.0,1.4997597826618576e-32],[-1.2011155542966555e-16,-1.0,-2.3891673840167802e-17],[-1.1314261122877005e-16,-1.0,-4.686520405326297e-17],[-1.018256599294603e-16,-1.0,-6.803773075690047e-17],[-8.659560562354935e-17,-1.0,-8.659560562354932e-17],[-6.80377307569005e-17,-1.0,-1.0182565992946028e-16],[-4.6865204053263054e-17,-1.0,-1.1314261122877e-16],[-2.389167384016784e-17,-1.0,-1.2011155542966553e-16],[-2.2496396739927864e-32,-1.0,-1.2246467991473532e-16],[2.3891673840167793e-17,-1.0,-1.2011155542966555e-16],[4.686520405326301e-17,-1.0,-1.1314261122877003e-16],[6.803773075690046e-17,-1.0,-1.018256599294603e-16],[8.65956056235493e-17,-1.0,-8.659560562354935e-17],[1.0182565992946028e-16,-1.0,-6.80377307569005e-17],[1.1314261122877e-16,-1.0,-4.686520405326306e-17],[1.2011155542966553e-16,-1.0,-2.3891673840167845e-17],[1.2246467991473532e-16,-1.0,-2.999519565323715e-32]]},"n":{"type":"vec3","data":[[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[-0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.0,1.0,-0.0],[0.19509032201612825,0.9807852804032304,0.0],[0.19134171618254486,0.9807852804032304,0.03806023374435662],[0.18023995550173696,0.9807852804032304,0.0746578340503426],[0.16221167441072887,0.9807852804032304,0.1083863756623696],[0.1379496896414715,0.9807852804032304,0.13794968964147147],[0.10838637566236961,0.9807852804032304,0.16221167441072887],[0.07465783405034261,0.9807852804032304,0.18023995550173696],[0.03806023374435663,0.9807852804032304,0.19134171618254486],[1.1945836920083893e-17,0.9807852804032304,0.19509032201612825],[-0.0380602337443566,0.9807852804032304,0.19134171618254486],[-0.07465783405034258,0.9807852804032304,0.18023995550173696],[-0.10838637566236956,0.9807852804032304,0.1622116744107289],[-0.13794968964147147,0.9807852804032304,0.1379496896414715],[-0.16221167441072887,0.9807852804032304,0.1083863756623696],[-0.18023995550173696,0.9807852804032304,0.07465783405034263],[-0.19134171618254486,0.9807852804032304,0.038060233744356686],[-0.19509032201612825,0.9807852804032304,2.3891673840167787e-17],[-0.19134171618254486,0.9807852804032304,-0.03806023374435664],[-0.18023995550173696,0.9807852804032304,-0.07465783405034258],[-0.1622116744107289,0.9807852804032304,-0.10838637566236956],[-0.13794968964147153,0.9807852804032304,-0.13794968964147147],[-0.1083863756623696,0.9807852804032304,-0.16221167441072887],[-0.07465783405034271,0.9807852804032304,-0.1802399555017369],[-0.03806023374435669,0.9807852804032304,-0.19134171618254484],[-3.583751076025168e-17,0.9807852804032304,-0.19509032201612825],[0.038060233744356624,0.9807852804032304,-0.19134171618254486],[0.07465783405034264,0.9807852804032304,-0.18023995550173694],[0.10838637566236953,0.9807852804032304,-0.1622116744107289],[0.13794968964147145,0.9807852804032304,-0.13794968964147153],[0.16221167441072887,0.9807852804032304,-0.1083863756623696],[0.1802399555017369,0.9807852804032304,-0.07465783405034272],[0.19134171618254484,0.9807852804032304,-0.03806023374435671],[0.19509032201612825,0.9807852804032304,-4.7783347680335573e-17],[0.3826834323650898,0.9238795325112867,0.0],[0.37533027751786524,0.9238795325112867,0.0746578340503426],[0.3535533905932738,0.9238795325112867,0.14644660940672624],[0.31818964514320847,0.9238795325112867,0.2126075236918141],[0.2705980500730985,0.9238795325112867,0.27059805007309845],[0.21260752369181415,0.9238795325112867,0.31818964514320847],[0.14644660940672627,0.9238795325112867,0.3535533905932738],[0.07465783405034264,0.9238795325112867,0.37533027751786524],[2.3432602026631493e-17,0.9238795325112867,0.3826834323650898],[-0.07465783405034258,0.9238795325112867,0.37533027751786524],[-0.1464466094067262,0.9238795325112867,0.3535533905932738],[-0.21260752369181402,0.9238795325112867,0.3181896451432086],[-0.27059805007309845,0.9238795325112867,0.2705980500730985],[-0.3181896451432085,0.9238795325112867,0.2126075236918141],[-0.3535533905932738,0.9238795325112867,0.1464466094067263],[-0.37533027751786524,0.9238795325112867,0.07465783405034274],[-0.3826834323650898,0.9238795325112867,4.6865204053262986e-17],[-0.37533027751786524,0.9238795325112867,-0.07465783405034264],[-0.3535533905932738,0.9238795325112867,-0.1464466094067262],[-0.3181896451432086,0.9238795325112867,-0.21260752369181402],[-0.27059805007309856,0.9238795325112867,-0.27059805007309845],[-0.2126075236918141,0.9238795325112867,-0.31818964514320847],[-0.14644660940672646,0.9238795325112867,-0.3535533905932737],[-0.07465783405034276,0.9238795325112867,-0.3753302775178652],[-7.029780607989448e-17,0.9238795325112867,-0.3826834323650898],[0.07465783405034263,0.9238795325112867,-0.37533027751786524],[0.14644660940672632,0.9238795325112867,-0.35355339059327373],[0.21260752369181396,0.9238795325112867,-0.3181896451432086],[0.27059805007309845,0.9238795325112867,-0.27059805007309856],[0.31818964514320847,0.9238795325112867,-0.2126075236918141],[0.3535533905932737,0.9238795325112867,-0.1464466094067265],[0.3753302775178652,0.9238795325112867,-0.07465783405034278],[0.3826834323650898,0.9238795325112867,-9.373040810652597e-17],[0.5555702330196022,0.8314696123025452,0.0],[0.5448951067758185,0.8314696123025452,0.1083863756623696],[0.5132799671593367,0.8314696123025452,0.2126075236918141],[0.4619397662556433,0.8314696123025452,0.3086582838174551],[0.39284747919355106,0.8314696123025452,0.392847479193551],[0.30865828381745514,0.8314696123025452,0.4619397662556433],[0.21260752369181413,0.8314696123025452,0.5132799671593367],[0.10838637566236964,0.8314696123025452,0.5448951067758185],[3.401886537845025e-17,0.8314696123025452,0.5555702330196022],[-0.10838637566236957,0.8314696123025452,0.5448951067758185],[-0.21260752369181407,0.8314696123025452,0.5132799671593367],[-0.3086582838174549,0.8314696123025452,0.4619397662556435],[-0.392847479193551,0.8314696123025452,0.39284747919355106],[-0.4619397662556434,0.8314696123025452,0.3086582838174551],[-0.5132799671593367,0.8314696123025452,0.21260752369181415],[-0.5448951067758185,0.8314696123025452,0.10838637566236979],[-0.5555702330196022,0.8314696123025452,6.80377307569005e-17],[-0.5448951067758185,0.8314696123025452,-0.10838637566236965],[-0.5132799671593368,0.8314696123025452,-0.21260752369181404],[-0.4619397662556435,0.8314696123025452,-0.3086582838174549],[-0.3928474791935511,0.8314696123025452,-0.392847479193551],[-0.3086582838174551,0.8314696123025452,-0.4619397662556433],[-0.2126075236918144,0.8314696123025452,-0.5132799671593365],[-0.10838637566236983,0.8314696123025452,-0.5448951067758185],[-1.0205659613535074e-16,0.8314696123025452,-0.5555702330196022],[0.10838637566236962,0.8314696123025452,-0.5448951067758185],[0.2126075236918142,0.8314696123025452,-0.5132799671593367],[0.30865828381745486,0.8314696123025452,-0.4619397662556435],[0.39284747919355095,0.8314696123025452,-0.3928474791935511],[0.4619397662556433,0.8314696123025452,-0.3086582838174551],[0.5132799671593365,0.8314696123025452,-0.21260752369181443],[0.5448951067758185,0.8314696123025452,-0.10838637566236986],[0.5555702330196022,0.8314696123025452,-1.36075461513801e-16],[0.7071067811865475,0.7071067811865476,0.0],[0.6935199226610737,0.7071067811865476,0.13794968964147147],[0.6532814824381882,0.7071067811865476,0.27059805007309845],[0.5879378012096793,0.7071067811865476,0.392847479193551],[0.5,0.7071067811865476,0.4999999999999999],[0.3928474791935511,0.7071067811865476,0.5879378012096793],[0.2705980500730985,0.7071067811865476,0.6532814824381882],[0.13794968964147153,0.7071067811865476,0.6935199226610737],[4.329780281177466e-17,0.7071067811865476,0.7071067811865475],[-0.13794968964147145,0.7071067811865476,0.6935199226610737],[-0.27059805007309845,0.7071067811865476,0.6532814824381882],[-0.39284747919355084,0.7071067811865476,0.5879378012096794],[-0.4999999999999999,0.7071067811865476,0.5],[-0.5879378012096794,0.7071067811865476,0.392847479193551],[-0.6532814824381882,0.7071067811865476,0.27059805007309856],[-0.6935199226610737,0.7071067811865476,0.13794968964147172],[-0.7071067811865475,0.7071067811865476,8.659560562354932e-17],[-0.6935199226610737,0.7071067811865476,-0.13794968964147156],[-0.6532814824381883,0.7071067811865476,-0.2705980500730984],[-0.5879378012096794,0.7071067811865476,-0.39284747919355084],[-0.5000000000000001,0.7071067811865476,-0.4999999999999999],[-0.392847479193551,0.7071067811865476,-0.5879378012096793],[-0.2705980500730989,0.7071067811865476,-0.6532814824381881],[-0.13794968964147178,0.7071067811865476,-0.6935199226610735],[-1.2989340843532398e-16,0.7071067811865476,-0.7071067811865475],[0.13794968964147153,0.7071067811865476,-0.6935199226610737],[0.2705980500730986,0.7071067811865476,-0.6532814824381881],[0.3928474791935508,0.7071067811865476,-0.5879378012096794],[0.49999999999999983,0.7071067811865476,-0.5000000000000001],[0.5879378012096793,0.7071067811865476,-0.392847479193551],[0.6532814824381881,0.7071067811865476,-0.2705980500730989],[0.6935199226610735,0.7071067811865476,-0.1379496896414718],[0.7071067811865475,0.7071067811865476,-1.7319121124709863e-16],[0.8314696123025452,0.5555702330196023,0.0],[0.8154931568489171,0.5555702330196023,0.16221167441072887],[0.7681777567114163,0.5555702330196023,0.31818964514320847],[0.6913417161825449,0.5555702330196023,0.4619397662556433],[0.5879378012096794,0.5555702330196023,0.5879378012096793],[0.4619397662556434,0.5555702330196023,0.6913417161825449],[0.3181896451432085,0.5555702330196023,0.7681777567114163],[0.16221167441072892,0.5555702330196023,0.8154931568489171],[5.091282996473014e-17,0.5555702330196023,0.8314696123025452],[-0.1622116744107288,0.5555702330196023,0.8154931568489171],[-0.31818964514320847,0.5555702330196023,0.7681777567114163],[-0.46193976625564315,0.5555702330196023,0.691341716182545],[-0.5879378012096793,0.5555702330196023,0.5879378012096794],[-0.691341716182545,0.5555702330196023,0.4619397662556433],[-0.7681777567114163,0.5555702330196023,0.3181896451432086],[-0.8154931568489171,0.5555702330196023,0.16221167441072917],[-0.8314696123025452,0.5555702330196023,1.0182565992946028e-16],[-0.8154931568489171,0.5555702330196023,-0.16221167441072895],[-0.7681777567114164,0.5555702330196023,-0.3181896451432084],[-0.691341716182545,0.5555702330196023,-0.46193976625564315],[-0.5879378012096795,0.5555702330196023,-0.5879378012096793],[-0.4619397662556433,0.5555702330196023,-0.6913417161825449],[-0.31818964514320897,0.5555702330196023,-0.7681777567114161],[-0.1622116744107292,0.5555702330196023,-0.815493156848917],[-1.527384898941904e-16,0.5555702330196023,-0.8314696123025452],[0.1622116744107289,0.5555702330196023,-0.8154931568489171],[0.3181896451432087,0.5555702330196023,-0.7681777567114162],[0.46193976625564304,0.5555702330196023,-0.691341716182545],[0.5879378012096792,0.5555702330196023,-0.5879378012096795],[0.6913417161825449,0.5555702330196023,-0.4619397662556433],[0.7681777567114161,0.5555702330196023,-0.318189645143209],[0.815493156848917,0.5555702330196023,-0.16221167441072926],[0.8314696123025452,0.5555702330196023,-2.0365131985892056e-16],[0.9238795325112867,0.38268343236508984,0.0],[0.9061274463528878,0.38268343236508984,0.18023995550173696],[0.8535533905932737,0.38268343236508984,0.3535533905932738],[0.7681777567114163,0.38268343236508984,0.5132799671593367],[0.6532814824381883,0.38268343236508984,0.6532814824381882],[0.5132799671593368,0.38268343236508984,0.7681777567114163],[0.35355339059327384,0.38268343236508984,0.8535533905932737],[0.18023995550173702,0.38268343236508984,0.9061274463528878],[5.657130561438501e-17,0.38268343236508984,0.9238795325112867],[-0.1802399555017369,0.38268343236508984,0.9061274463528878],[-0.35355339059327373,0.38268343236508984,0.8535533905932737],[-0.5132799671593365,0.38268343236508984,0.7681777567114165],[-0.6532814824381882,0.38268343236508984,0.6532814824381883],[-0.7681777567114164,0.38268343236508984,0.5132799671593367],[-0.8535533905932737,0.38268343236508984,0.35355339059327384],[-0.9061274463528878,0.38268343236508984,0.1802399555017373],[-0.9238795325112867,0.38268343236508984,1.1314261122877003e-16],[-0.9061274463528878,0.38268343236508984,-0.18023995550173705],[-0.8535533905932738,0.38268343236508984,-0.3535533905932737],[-0.7681777567114165,0.38268343236508984,-0.5132799671593365],[-0.6532814824381884,0.38268343236508984,-0.6532814824381882],[-0.5132799671593367,0.38268343236508984,-0.7681777567114163],[-0.3535533905932743,0.38268343236508984,-0.8535533905932735],[-0.18023995550173735,0.38268343236508984,-0.9061274463528877],[-1.6971391684315505e-16,0.38268343236508984,-0.9238795325112867],[0.18023995550173702,0.38268343236508984,-0.9061274463528878],[0.35355339059327395,0.38268343236508984,-0.8535533905932736],[0.5132799671593364,0.38268343236508984,-0.7681777567114165],[0.6532814824381881,0.38268343236508984,-0.6532814824381884],[0.7681777567114163,0.38268343236508984,-0.5132799671593367],[0.8535533905932735,0.38268343236508984,-0.35355339059327434],[0.9061274463528877,0.38268343236508984,-0.18023995550173738],[0.9238795325112867,0.38268343236508984,-2.2628522245754005e-16],[0.9807852804032304,0.19509032201612833,0.0],[0.9619397662556434,0.19509032201612833,0.19134171618254486],[0.9061274463528878,0.19509032201612833,0.37533027751786524],[0.8154931568489171,0.19509032201612833,0.5448951067758185],[0.6935199226610738,0.19509032201612833,0.6935199226610737],[0.5448951067758186,0.19509032201612833,0.8154931568489171],[0.3753302775178653,0.19509032201612833,0.9061274463528878],[0.19134171618254495,0.19509032201612833,0.9619397662556434],[6.005577771483278e-17,0.19509032201612833,0.9807852804032304],[-0.1913417161825448,0.19509032201612833,0.9619397662556434],[-0.3753302775178652,0.19509032201612833,0.9061274463528878],[-0.5448951067758184,0.19509032201612833,0.8154931568489173],[-0.6935199226610737,0.19509032201612833,0.6935199226610738],[-0.8154931568489172,0.19509032201612833,0.5448951067758185],[-0.9061274463528878,0.19509032201612833,0.37533027751786535],[-0.9619397662556434,0.19509032201612833,0.19134171618254522],[-0.9807852804032304,0.19509032201612833,1.2011155542966555e-16],[-0.9619397662556434,0.19509032201612833,-0.19134171618254497],[-0.9061274463528879,0.19509032201612833,-0.37533027751786513],[-0.8154931568489173,0.19509032201612833,-0.5448951067758184],[-0.6935199226610739,0.19509032201612833,-0.6935199226610737],[-0.5448951067758185,0.19509032201612833,-0.8154931568489171],[-0.3753302775178658,0.19509032201612833,-0.9061274463528876],[-0.19134171618254528,0.19509032201612833,-0.9619397662556433],[-1.8016733314449831e-16,0.19509032201612833,-0.9807852804032304],[0.19134171618254492,0.19509032201612833,-0.9619397662556434],[0.37533027751786546,0.19509032201612833,-0.9061274463528877],[0.5448951067758183,0.19509032201612833,-0.8154931568489173],[0.6935199226610735,0.19509032201612833,-0.6935199226610739],[0.8154931568489171,0.19509032201612833,-0.5448951067758185],[0.9061274463528876,0.19509032201612833,-0.37533027751786585],[0.9619397662556433,0.19509032201612833,-0.19134171618254533],[0.9807852804032304,0.19509032201612833,-2.402231108593311e-16],[1.0,6.123233995736766e-17,0.0],[0.9807852804032304,6.123233995736766e-17,0.19509032201612825],[0.9238795325112867,6.123233995736766e-17,0.3826834323650898],[0.8314696123025452,6.123233995736766e-17,0.5555702330196022],[0.7071067811865476,6.123233995736766e-17,0.7071067811865475],[0.5555702330196023,6.123233995736766e-17,0.8314696123025452],[0.38268343236508984,6.123233995736766e-17,0.9238795325112867],[0.19509032201612833,6.123233995736766e-17,0.9807852804032304],[6.123233995736766e-17,6.123233995736766e-17,1.0],[-0.1950903220161282,6.123233995736766e-17,0.9807852804032304],[-0.3826834323650897,6.123233995736766e-17,0.9238795325112867],[-0.555570233019602,6.123233995736766e-17,0.8314696123025455],[-0.7071067811865475,6.123233995736766e-17,0.7071067811865476],[-0.8314696123025453,6.123233995736766e-17,0.5555702330196022],[-0.9238795325112867,6.123233995736766e-17,0.3826834323650899],[-0.9807852804032304,6.123233995736766e-17,0.1950903220161286],[-1.0,6.123233995736766e-17,1.2246467991473532e-16],[-0.9807852804032304,6.123233995736766e-17,-0.19509032201612836],[-0.9238795325112868,6.123233995736766e-17,-0.38268343236508967],[-0.8314696123025455,6.123233995736766e-17,-0.555570233019602],[-0.7071067811865477,6.123233995736766e-17,-0.7071067811865475],[-0.5555702330196022,6.123233995736766e-17,-0.8314696123025452],[-0.38268343236509034,6.123233995736766e-17,-0.9238795325112865],[-0.19509032201612866,6.123233995736766e-17,-0.9807852804032303],[-1.8369701987210297e-16,6.123233995736766e-17,-1.0],[0.1950903220161283,6.123233995736766e-17,-0.9807852804032304],[0.38268343236509,6.123233995736766e-17,-0.9238795325112866],[0.5555702330196018,6.123233995736766e-17,-0.8314696123025455],[0.7071067811865474,6.123233995736766e-17,-0.7071067811865477],[0.8314696123025452,6.123233995736766e-17,-0.5555702330196022],[0.9238795325112865,6.123233995736766e-17,-0.3826834323650904],[0.9807852804032303,6.123233995736766e-17,-0.19509032201612872],[1.0,6.123233995736766e-17,-2.4492935982947064e-16],[0.9807852804032304,-0.1950903220161282,0.0],[0.9619397662556434,-0.1950903220161282,0.19134171618254486],[0.9061274463528878,-0.1950903220161282,0.37533027751786524],[0.8154931568489171,-0.1950903220161282,0.5448951067758185],[0.6935199226610738,-0.1950903220161282,0.6935199226610737],[0.5448951067758186,-0.1950903220161282,0.8154931568489171],[0.3753302775178653,-0.1950903220161282,0.9061274463528878],[0.19134171618254495,-0.1950903220161282,0.9619397662556434],[6.005577771483278e-17,-0.1950903220161282,0.9807852804032304],[-0.1913417161825448,-0.1950903220161282,0.9619397662556434],[-0.3753302775178652,-0.1950903220161282,0.9061274463528878],[-0.5448951067758184,-0.1950903220161282,0.8154931568489173],[-0.6935199226610737,-0.1950903220161282,0.6935199226610738],[-0.8154931568489172,-0.1950903220161282,0.5448951067758185],[-0.9061274463528878,-0.1950903220161282,0.37533027751786535],[-0.9619397662556434,-0.1950903220161282,0.19134171618254522],[-0.9807852804032304,-0.1950903220161282,1.2011155542966555e-16],[-0.9619397662556434,-0.1950903220161282,-0.19134171618254497],[-0.9061274463528879,-0.1950903220161282,-0.37533027751786513],[-0.8154931568489173,-0.1950903220161282,-0.5448951067758184],[-0.6935199226610739,-0.1950903220161282,-0.6935199226610737],[-0.5448951067758185,-0.1950903220161282,-0.8154931568489171],[-0.3753302775178658,-0.1950903220161282,-0.9061274463528876],[-0.19134171618254528,-0.1950903220161282,-0.9619397662556433],[-1.8016733314449831e-16,-0.1950903220161282,-0.9807852804032304],[0.19134171618254492,-0.1950903220161282,-0.9619397662556434],[0.37533027751786546,-0.1950903220161282,-0.9061274463528877],[0.5448951067758183,-0.1950903220161282,-0.8154931568489173],[0.6935199226610735,-0.1950903220161282,-0.6935199226610739],[0.8154931568489171,-0.1950903220161282,-0.5448951067758185],[0.9061274463528876,-0.1950903220161282,-0.37533027751786585],[0.9619397662556433,-0.1950903220161282,-0.19134171618254533],[0.9807852804032304,-0.1950903220161282,-2.402231108593311e-16],[0.9238795325112867,-0.3826834323650897,0.0],[0.9061274463528878,-0.3826834323650897,0.18023995550173696],[0.8535533905932737,-0.3826834323650897,0.3535533905932738],[0.7681777567114163,-0.3826834323650897,0.5132799671593367],[0.6532814824381883,-0.3826834323650897,0.6532814824381882],[0.5132799671593368,-0.3826834323650897,0.7681777567114163],[0.35355339059327384,-0.3826834323650897,0.8535533905932737],[0.18023995550173702,-0.3826834323650897,0.9061274463528878],[5.657130561438501e-17,-0.3826834323650897,0.9238795325112867],[-0.1802399555017369,-0.3826834323650897,0.9061274463528878],[-0.35355339059327373,-0.3826834323650897,0.8535533905932737],[-0.5132799671593365,-0.3826834323650897,0.7681777567114165],[-0.6532814824381882,-0.3826834323650897,0.6532814824381883],[-0.7681777567114164,-0.3826834323650897,0.5132799671593367],[-0.8535533905932737,-0.3826834323650897,0.35355339059327384],[-0.9061274463528878,-0.3826834323650897,0.1802399555017373],[-0.9238795325112867,-0.3826834323650897,1.1314261122877003e-16],[-0.9061274463528878,-0.3826834323650897,-0.18023995550173705],[-0.8535533905932738,-0.3826834323650897,-0.3535533905932737],[-0.7681777567114165,-0.3826834323650897,-0.5132799671593365],[-0.6532814824381884,-0.3826834323650897,-0.6532814824381882],[-0.5132799671593367,-0.3826834323650897,-0.7681777567114163],[-0.3535533905932743,-0.3826834323650897,-0.8535533905932735],[-0.18023995550173735,-0.3826834323650897,-0.9061274463528877],[-1.6971391684315505e-16,-0.3826834323650897,-0.9238795325112867],[0.18023995550173702,-0.3826834323650897,-0.9061274463528878],[0.35355339059327395,-0.3826834323650897,-0.8535533905932736],[0.5132799671593364,-0.3826834323650897,-0.7681777567114165],[0.6532814824381881,-0.3826834323650897,-0.6532814824381884],[0.7681777567114163,-0.3826834323650897,-0.5132799671593367],[0.8535533905932735,-0.3826834323650897,-0.35355339059327434],[0.9061274463528877,-0.3826834323650897,-0.18023995550173738],[0.9238795325112867,-0.3826834323650897,-2.2628522245754005e-16],[0.8314696123025455,-0.555570233019602,0.0],[0.8154931568489173,-0.555570233019602,0.1622116744107289],[0.7681777567114165,-0.555570233019602,0.3181896451432086],[0.691341716182545,-0.555570233019602,0.4619397662556435],[0.5879378012096795,-0.555570233019602,0.5879378012096794],[0.46193976625564354,-0.555570233019602,0.691341716182545],[0.31818964514320863,-0.555570233019602,0.7681777567114165],[0.16221167441072898,-0.555570233019602,0.8154931568489173],[5.091282996473015e-17,-0.555570233019602,0.8314696123025455],[-0.16221167441072887,-0.555570233019602,0.8154931568489173],[-0.3181896451432085,-0.555570233019602,0.7681777567114165],[-0.46193976625564326,-0.555570233019602,0.6913417161825453],[-0.5879378012096794,-0.555570233019602,0.5879378012096795],[-0.6913417161825451,-0.555570233019602,0.4619397662556435],[-0.7681777567114165,-0.555570233019602,0.3181896451432087],[-0.8154931568489173,-0.555570233019602,0.1622116744107292],[-0.8314696123025455,-0.555570233019602,1.018256599294603e-16],[-0.8154931568489173,-0.555570233019602,-0.162211674410729],[-0.7681777567114166,-0.555570233019602,-0.31818964514320847],[-0.6913417161825453,-0.555570233019602,-0.46193976625564326],[-0.5879378012096796,-0.555570233019602,-0.5879378012096794],[-0.4619397662556435,-0.555570233019602,-0.691341716182545],[-0.318189645143209,-0.555570233019602,-0.7681777567114163],[-0.16221167441072926,-0.555570233019602,-0.8154931568489172],[-1.5273848989419045e-16,-0.555570233019602,-0.8314696123025455],[0.16221167441072895,-0.555570233019602,-0.8154931568489173],[0.31818964514320874,-0.555570233019602,-0.7681777567114164],[0.4619397662556432,-0.555570233019602,-0.6913417161825453],[0.5879378012096794,-0.555570233019602,-0.5879378012096796],[0.691341716182545,-0.555570233019602,-0.4619397662556435],[0.7681777567114163,-0.555570233019602,-0.3181896451432091],[0.8154931568489172,-0.555570233019602,-0.16221167441072928],[0.8314696123025455,-0.555570233019602,-2.036513198589206e-16],[0.7071067811865476,-0.7071067811865475,0.0],[0.6935199226610738,-0.7071067811865475,0.1379496896414715],[0.6532814824381883,-0.7071067811865475,0.2705980500730985],[0.5879378012096794,-0.7071067811865475,0.39284747919355106],[0.5000000000000001,-0.7071067811865475,0.5],[0.3928474791935512,-0.7071067811865475,0.5879378012096794],[0.27059805007309856,-0.7071067811865475,0.6532814824381883],[0.13794968964147156,-0.7071067811865475,0.6935199226610738],[4.329780281177467e-17,-0.7071067811865475,0.7071067811865476],[-0.13794968964147147,-0.7071067811865475,0.6935199226610738],[-0.2705980500730985,-0.7071067811865475,0.6532814824381883],[-0.39284747919355095,-0.7071067811865475,0.5879378012096795],[-0.5,-0.7071067811865475,0.5000000000000001],[-0.5879378012096794,-0.7071067811865475,0.39284747919355106],[-0.6532814824381883,-0.7071067811865475,0.2705980500730986],[-0.6935199226610738,-0.7071067811865475,0.13794968964147175],[-0.7071067811865476,-0.7071067811865475,8.659560562354934e-17],[-0.6935199226610738,-0.7071067811865475,-0.13794968964147158],[-0.6532814824381884,-0.7071067811865475,-0.27059805007309845],[-0.5879378012096795,-0.7071067811865475,-0.39284747919355095],[-0.5000000000000001,-0.7071067811865475,-0.5],[-0.39284747919355106,-0.7071067811865475,-0.5879378012096794],[-0.2705980500730989,-0.7071067811865475,-0.6532814824381882],[-0.1379496896414718,-0.7071067811865475,-0.6935199226610737],[-1.29893408435324e-16,-0.7071067811865475,-0.7071067811865476],[0.13794968964147153,-0.7071067811865475,-0.6935199226610738],[0.2705980500730987,-0.7071067811865475,-0.6532814824381882],[0.39284747919355084,-0.7071067811865475,-0.5879378012096795],[0.4999999999999999,-0.7071067811865475,-0.5000000000000001],[0.5879378012096794,-0.7071067811865475,-0.39284747919355106],[0.6532814824381882,-0.7071067811865475,-0.27059805007309895],[0.6935199226610737,-0.7071067811865475,-0.13794968964147183],[0.7071067811865476,-0.7071067811865475,-1.7319121124709868e-16],[0.5555702330196022,-0.8314696123025453,0.0],[0.5448951067758185,-0.8314696123025453,0.1083863756623696],[0.5132799671593367,-0.8314696123025453,0.2126075236918141],[0.4619397662556433,-0.8314696123025453,0.3086582838174551],[0.39284747919355106,-0.8314696123025453,0.392847479193551],[0.30865828381745514,-0.8314696123025453,0.4619397662556433],[0.21260752369181413,-0.8314696123025453,0.5132799671593367],[0.10838637566236964,-0.8314696123025453,0.5448951067758185],[3.401886537845025e-17,-0.8314696123025453,0.5555702330196022],[-0.10838637566236957,-0.8314696123025453,0.5448951067758185],[-0.21260752369181407,-0.8314696123025453,0.5132799671593367],[-0.3086582838174549,-0.8314696123025453,0.4619397662556435],[-0.392847479193551,-0.8314696123025453,0.39284747919355106],[-0.4619397662556434,-0.8314696123025453,0.3086582838174551],[-0.5132799671593367,-0.8314696123025453,0.21260752369181415],[-0.5448951067758185,-0.8314696123025453,0.10838637566236979],[-0.5555702330196022,-0.8314696123025453,6.80377307569005e-17],[-0.5448951067758185,-0.8314696123025453,-0.10838637566236965],[-0.5132799671593368,-0.8314696123025453,-0.21260752369181404],[-0.4619397662556435,-0.8314696123025453,-0.3086582838174549],[-0.3928474791935511,-0.8314696123025453,-0.392847479193551],[-0.3086582838174551,-0.8314696123025453,-0.4619397662556433],[-0.2126075236918144,-0.8314696123025453,-0.5132799671593365],[-0.10838637566236983,-0.8314696123025453,-0.5448951067758185],[-1.0205659613535074e-16,-0.8314696123025453,-0.5555702330196022],[0.10838637566236962,-0.8314696123025453,-0.5448951067758185],[0.2126075236918142,-0.8314696123025453,-0.5132799671593367],[0.30865828381745486,-0.8314696123025453,-0.4619397662556435],[0.39284747919355095,-0.8314696123025453,-0.3928474791935511],[0.4619397662556433,-0.8314696123025453,-0.3086582838174551],[0.5132799671593365,-0.8314696123025453,-0.21260752369181443],[0.5448951067758185,-0.8314696123025453,-0.10838637566236986],[0.5555702330196022,-0.8314696123025453,-1.36075461513801e-16],[0.3826834323650899,-0.9238795325112867,0.0],[0.37533027751786535,-0.9238795325112867,0.07465783405034263],[0.35355339059327384,-0.9238795325112867,0.1464466094067263],[0.3181896451432086,-0.9238795325112867,0.21260752369181415],[0.2705980500730986,-0.9238795325112867,0.27059805007309856],[0.2126075236918142,-0.9238795325112867,0.3181896451432086],[0.1464466094067263,-0.9238795325112867,0.35355339059327384],[0.07465783405034265,-0.9238795325112867,0.37533027751786535],[2.34326020266315e-17,-0.9238795325112867,0.3826834323650899],[-0.0746578340503426,-0.9238795325112867,0.37533027751786535],[-0.14644660940672627,-0.9238795325112867,0.35355339059327384],[-0.21260752369181407,-0.9238795325112867,0.3181896451432087],[-0.27059805007309856,-0.9238795325112867,0.2705980500730986],[-0.31818964514320863,-0.9238795325112867,0.21260752369181415],[-0.35355339059327384,-0.9238795325112867,0.14644660940672632],[-0.37533027751786535,-0.9238795325112867,0.07465783405034276],[-0.3826834323650899,-0.9238795325112867,4.6865204053263e-17],[-0.37533027751786535,-0.9238795325112867,-0.07465783405034267],[-0.3535533905932739,-0.9238795325112867,-0.14644660940672624],[-0.3181896451432087,-0.9238795325112867,-0.21260752369181407],[-0.2705980500730986,-0.9238795325112867,-0.27059805007309856],[-0.21260752369181415,-0.9238795325112867,-0.3181896451432086],[-0.1464466094067265,-0.9238795325112867,-0.3535533905932738],[-0.07465783405034278,-0.9238795325112867,-0.3753302775178653],[-7.029780607989449e-17,-0.9238795325112867,-0.3826834323650899],[0.07465783405034264,-0.9238795325112867,-0.37533027751786535],[0.14644660940672638,-0.9238795325112867,-0.35355339059327384],[0.21260752369181404,-0.9238795325112867,-0.3181896451432087],[0.2705980500730985,-0.9238795325112867,-0.2705980500730986],[0.3181896451432086,-0.9238795325112867,-0.21260752369181415],[0.3535533905932738,-0.9238795325112867,-0.14644660940672652],[0.3753302775178653,-0.9238795325112867,-0.0746578340503428],[0.3826834323650899,-0.9238795325112867,-9.3730408106526e-17],[0.1950903220161286,-0.9807852804032304,0.0],[0.19134171618254522,-0.9807852804032304,0.038060233744356686],[0.1802399555017373,-0.9807852804032304,0.07465783405034274],[0.16221167441072917,-0.9807852804032304,0.10838637566236979],[0.13794968964147175,-0.9807852804032304,0.13794968964147172],[0.10838637566236982,-0.9807852804032304,0.16221167441072917],[0.07465783405034275,-0.9807852804032304,0.1802399555017373],[0.0380602337443567,-0.9807852804032304,0.19134171618254522],[1.1945836920083915e-17,-0.9807852804032304,0.1950903220161286],[-0.03806023374435667,-0.9807852804032304,0.19134171618254522],[-0.07465783405034272,-0.9807852804032304,0.1802399555017373],[-0.10838637566236975,-0.9807852804032304,0.1622116744107292],[-0.13794968964147172,-0.9807852804032304,0.13794968964147175],[-0.16221167441072917,-0.9807852804032304,0.10838637566236979],[-0.1802399555017373,-0.9807852804032304,0.07465783405034276],[-0.19134171618254522,-0.9807852804032304,0.038060233744356756],[-0.1950903220161286,-0.9807852804032304,2.389167384016783e-17],[-0.19134171618254522,-0.9807852804032304,-0.03806023374435671],[-0.18023995550173733,-0.9807852804032304,-0.07465783405034272],[-0.1622116744107292,-0.9807852804032304,-0.10838637566236975],[-0.13794968964147178,-0.9807852804032304,-0.13794968964147172],[-0.10838637566236979,-0.9807852804032304,-0.16221167441072917],[-0.07465783405034285,-0.9807852804032304,-0.18023995550173724],[-0.03806023374435676,-0.9807852804032304,-0.1913417161825452],[-3.583751076025174e-17,-0.9807852804032304,-0.1950903220161286],[0.03806023374435669,-0.9807852804032304,-0.19134171618254522],[0.07465783405034278,-0.9807852804032304,-0.18023995550173727],[0.10838637566236974,-0.9807852804032304,-0.1622116744107292],[0.13794968964147172,-0.9807852804032304,-0.13794968964147178],[0.16221167441072917,-0.9807852804032304,-0.10838637566236979],[0.18023995550173724,-0.9807852804032304,-0.07465783405034286],[0.1913417161825452,-0.9807852804032304,-0.038060233744356776],[0.1950903220161286,-0.9807852804032304,-4.778334768033566e-17],[1.2246467991473532e-16,-1.0,0.0],[1.2011155542966555e-16,-1.0,2.3891673840167787e-17],[1.1314261122877003e-16,-1.0,4.6865204053262986e-17],[1.0182565992946028e-16,-1.0,6.80377307569005e-17],[8.659560562354934e-17,-1.0,8.659560562354932e-17],[6.803773075690051e-17,-1.0,1.0182565992946028e-16],[4.686520405326299e-17,-1.0,1.1314261122877003e-16],[2.3891673840167796e-17,-1.0,1.2011155542966555e-16],[7.498798913309288e-33,-1.0,1.2246467991473532e-16],[-2.389167384016778e-17,-1.0,1.2011155542966555e-16],[-4.6865204053262974e-17,-1.0,1.1314261122877003e-16],[-6.803773075690047e-17,-1.0,1.018256599294603e-16],[-8.659560562354932e-17,-1.0,8.659560562354934e-17],[-1.0182565992946029e-16,-1.0,6.80377307569005e-17],[-1.1314261122877003e-16,-1.0,4.6865204053263e-17],[-1.2011155542966555e-16,-1.0,2.389167384016783e-17],[-1.2246467991473532e-16,-1.0,1.4997597826618576e-32],[-1.2011155542966555e-16,-1.0,-2.3891673840167802e-17],[-1.1314261122877005e-16,-1.0,-4.686520405326297e-17],[-1.018256599294603e-16,-1.0,-6.803773075690047e-17],[-8.659560562354935e-17,-1.0,-8.659560562354932e-17],[-6.80377307569005e-17,-1.0,-1.0182565992946028e-16],[-4.6865204053263054e-17,-1.0,-1.1314261122877e-16],[-2.389167384016784e-17,-1.0,-1.2011155542966553e-16],[-2.2496396739927864e-32,-1.0,-1.2246467991473532e-16],[2.3891673840167793e-17,-1.0,-1.2011155542966555e-16],[4.686520405326301e-17,-1.0,-1.1314261122877003e-16],[6.803773075690046e-17,-1.0,-1.018256599294603e-16],[8.65956056235493e-17,-1.0,-8.659560562354935e-17],[1.0182565992946028e-16,-1.0,-6.80377307569005e-17],[1.1314261122877e-16,-1.0,-4.686520405326306e-17],[1.2011155542966553e-16,-1.0,-2.3891673840167845e-17],[1.2246467991473532e-16,-1.0,-2.999519565323715e-32]]},"i":{"type":"u32","data":[0,1,33,1,34,33,1,2,34,2,35,34,2,3,35,3,36,35,3,4,36,4,37,36,4,5,37,5,38,37,5,6,38,6,39,38,6,7,39,7,40,39,7,8,40,8,41,40,8,9,41,9,42,41,9,10,42,10,43,42,10,11,43,11,44,43,11,12,44,12,45,44,12,13,45,13,46,45,13,14,46,14,47,46,14,15,47,15,48,47,15,16,48,16,49,48,16,17,49,17,50,49,17,18,50,18,51,50,18,19,51,19,52,51,19,20,52,20,53,52,20,21,53,21,54,53,21,22,54,22,55,54,22,23,55,23,56,55,23,24,56,24,57,56,24,25,57,25,58,57,25,26,58,26,59,58,26,27,59,27,60,59,27,28,60,28,61,60,28,29,61,29,62,61,29,30,62,30,63,62,30,31,63,31,64,63,31,32,64,32,65,64,33,34,66,34,67,66,34,35,67,35,68,67,35,36,68,36,69,68,36,37,69,37,70,69,37,38,70,38,71,70,38,39,71,39,72,71,39,40,72,40,73,72,40,41,73,41,74,73,41,42,74,42,75,74,42,43,75,43,76,75,43,44,76,44,77,76,44,45,77,45,78,77,45,46,78,46,79,78,46,47,79,47,80,79,47,48,80,48,81,80,48,49,81,49,82,81,49,50,82,50,83,82,50,51,83,51,84,83,51,52,84,52,85,84,52,53,85,53,86,85,53,54,86,54,87,86,54,55,87,55,88,87,55,56,88,56,89,88,56,57,89,57,90,89,57,58,90,58,91,90,58,59,91,59,92,91,59,60,92,60,93,92,60,61,93,61,94,93,61,62,94,62,95,94,62,63,95,63,96,95,63,64,96,64,97,96,64,65,97,65,98,97,66,67,99,67,100,99,67,68,100,68,101,100,68,69,101,69,102,101,69,70,102,70,103,102,70,71,103,71,104,103,71,72,104,72,105,104,72,73,105,73,106,105,73,74,106,74,107,106,74,75,107,75,108,107,75,76,108,76,109,108,76,77,109,77,110,109,77,78,110,78,111,110,78,79,111,79,112,111,79,80,112,80,113,112,80,81,113,81,114,113,81,82,114,82,115,114,82,83,115,83,116,115,83,84,116,84,117,116,84,85,117,85,118,117,85,86,118,86,119,118,86,87,119,87,120,119,87,88,120,88,121,120,88,89,121,89,122,121,89,90,122,90,123,122,90,91,123,91,124,123,91,92,124,92,125,124,92,93,125,93,126,125,93,94,126,94,127,126,94,95,127,95,128,127,95,96,128,96,129,128,96,97,129,97,130,129,97,98,130,98,131,130,99,100,132,100,133,132,100,101,133,101,134,133,101,102,134,102,135,134,102,103,135,103,136,135,103,104,136,104,137,136,104,105,137,105,138,137,105,106,138,106,139,138,106,107,139,107,140,139,107,108,140,108,141,140,108,109,141,109,142,141,109,110,142,110,143,142,110,111,143,111,144,143,111,112,144,112,145,144,112,113,145,113,146,145,113,114,146,114,147,146,114,115,147,115,148,147,115,116,148,116,149,148,116,117,149,117,150,149,117,118,150,118,151,150,118,119,151,119,152,151,119,120,152,120,153,152,120,121,153,121,154,153,121,122,154,122,155,154,122,123,155,123,156,155,123,124,156,124,157,156,124,125,157,125,158,157,125,126,158,126,159,158,126,127,159,127,160,159,127,128,160,128,161,160,128,129,161,129,162,161,129,130,162,130,163,162,130,131,163,131,164,163,132,133,165,133,166,165,133,134,166,134,167,166,134,135,167,135,168,167,135,136,168,136,169,168,136,137,169,137,170,169,137,138,170,138,171,170,138,139,171,139,172,171,139,140,172,140,173,172,140,141,173,141,174,173,141,142,174,142,175,174,142,143,175,143,176,175,143,144,176,144,177,176,144,145,177,145,178,177,145,146,178,146,179,178,146,147,179,147,180,179,147,148,180,148,181,180,148,149,181,149,182,181,149,150,182,150,183,182,150,151,183,151,184,183,151,152,184,152,185,184,152,153,185,153,186,185,153,154,186,154,187,186,154,155,187,155,188,187,155,156,188,156,189,188,156,157,189,157,190,189,157,158,190,158,191,190,158,159,191,159,192,191,159,160,192,160,193,192,160,161,193,161,194,193,161,162,194,162,195,194,162,163,195,163,196,195,163,164,196,164,197,196,165,166,198,166,199,198,166,167,199,167,200,199,167,168,200,168,201,200,168,169,201,169,202,201,169,170,202,170,203,202,170,171,203,171,204,203,171,172,204,172,205,204,172,173,205,173,206,205,173,174,206,174,207,206,174,175,207,175,208,207,175,176,208,176,209,208,176,177,209,177,210,209,177,178,210,178,211,210,178,179,211,179,212,211,179,180,212,180,213,212,180,181,213,181,214,213,181,182,214,182,215,214,182,183,215,183,216,215,183,184,216,184,217,216,184,185,217,185,218,217,185,186,218,186,219,218,186,187,219,187,220,219,187,188,220,188,221,220,188,189,221,189,222,221,189,190,222,190,223,222,190,191,223,191,224,223,191,192,224,192,225,224,192,193,225,193,226,225,193,194,226,194,227,226,194,195,227,195,228,227,195,196,228,196,229,228,196,197,229,197,230,229,198,199,231,199,232,231,199,200,232,200,233,232,200,201,233,201,234,233,201,202,234,202,235,234,202,203,235,203,236,235,203,204,236,204,237,236,204,205,237,205,238,237,205,206,238,206,239,238,206,207,239,207,240,239,207,208,240,208,241,240,208,209,241,209,242,241,209,210,242,210,243,242,210,211,243,211,244,243,211,212,244,212,245,244,212,213,245,213,246,245,213,214,246,214,247,246,214,215,247,215,248,247,215,216,248,216,249,248,216,217,249,217,250,249,217,218,250,218,251,250,218,219,251,219,252,251,219,220,252,220,253,252,220,221,253,221,254,253,221,222,254,222,255,254,222,223,255,223,256,255,223,224,256,224,257,256,224,225,257,225,258,257,225,226,258,226,259,258,226,227,259,227,260,259,227,228,260,228,261,260,228,229,261,229,262,261,229,230,262,230,263,262,231,232,264,232,265,264,232,233,265,233,266,265,233,234,266,234,267,266,234,235,267,235,268,267,235,236,268,236,269,268,236,237,269,237,270,269,237,238,270,238,271,270,238,239,271,239,272,271,239,240,272,240,273,272,240,241,273,241,274,273,241,242,274,242,275,274,242,243,275,243,276,275,243,244,276,244,277,276,244,245,277,245,278,277,245,246,278,246,279,278,246,247,279,247,280,279,247,248,280,248,281,280,248,249,281,249,282,281,249,250,282,250,283,282,250,251,283,251,284,283,251,252,284,252,285,284,252,253,285,253,286,285,253,254,286,254,287,286,254,255,287,255,288,287,255,256,288,256,289,288,256,257,289,257,290,289,257,258,290,258,291,290,258,259,291,259,292,291,259,260,292,260,293,292,260,261,293,261,294,293,261,262,294,262,295,294,262,263,295,263,296,295,264,265,297,265,298,297,265,266,298,266,299,298,266,267,299,267,300,299,267,268,300,268,301,300,268,269,301,269,302,301,269,270,302,270,303,302,270,271,303,271,304,303,271,272,304,272,305,304,272,273,305,273,306,305,273,274,306,274,307,306,274,275,307,275,308,307,275,276,308,276,309,308,276,277,309,277,310,309,277,278,310,278,311,310,278,279,311,279,312,311,279,280,312,280,313,312,280,281,313,281,314,313,281,282,314,282,315,314,282,283,315,283,316,315,283,284,316,284,317,316,284,285,317,285,318,317,285,286,318,286,319,318,286,287,319,287,320,319,287,288,320,288,321,320,288,289,321,289,322,321,289,290,322,290,323,322,290,291,323,291,324,323,291,292,324,292,325,324,292,293,325,293,326,325,293,294,326,294,327,326,294,295,327,295,328,327,295,296,328,296,329,328,297,298,330,298,331,330,298,299,331,299,332,331,299,300,332,300,333,332,300,301,333,301,334,333,301,302,334,302,335,334,302,303,335,303,336,335,303,304,336,304,337,336,304,305,337,305,338,337,305,306,338,306,339,338,306,307,339,307,340,339,307,308,340,308,341,340,308,309,341,309,342,341,309,310,342,310,343,342,310,311,343,311,344,343,311,312,344,312,345,344,312,313,345,313,346,345,313,314,346,314,347,346,314,315,347,315,348,347,315,316,348,316,349,348,316,317,349,317,350,349,317,318,350,318,351,350,318,319,351,319,352,351,319,320,352,320,353,352,320,321,353,321,354,353,321,322,354,322,355,354,322,323,355,323,356,355,323,324,356,324,357,356,324,325,357,325,358,357,325,326,358,326,359,358,326,327,359,327,360,359,327,328,360,328,361,360,328,329,361,329,362,361,330,331,363,331,364,363,331,332,364,332,365,364,332,333,365,333,366,365,333,334,366,334,367,366,334,335,367,335,368,367,335,336,368,336,369,368,336,337,369,337,370,369,337,338,370,338,371,370,338,339,371,339,372,371,339,340,372,340,373,372,340,341,373,341,374,373,341,342,374,342,375,374,342,343,375,343,376,375,343,344,376,344,377,376,344,345,377,345,378,377,345,346,378,346,379,378,346,347,379,347,380,379,347,348,380,348,381,380,348,349,381,349,382,381,349,350,382,350,383,382,350,351,383,351,384,383,351,352,384,352,385,384,352,353,385,353,386,385,353,354,386,354,387,386,354,355,387,355,388,387,355,356,388,356,389,388,356,357,389,357,390,389,357,358,390,358,391,390,358,359,391,359,392,391,359,360,392,360,393,392,360,361,393,361,394,393,361,362,394,362,395,394,363,364,396,364,397,396,364,365,397,365,398,397,365,366,398,366,399,398,366,367,399,367,400,399,367,368,400,368,401,400,368,369,401,369,402,401,369,370,402,370,403,402,370,371,403,371,404,403,371,372,404,372,405,404,372,373,405,373,406,405,373,374,406,374,407,406,374,375,407,375,408,407,375,376,408,376,409,408,376,377,409,377,410,409,377,378,410,378,411,410,378,379,411,379,412,411,379,380,412,380,413,412,380,381,413,381,414,413,381,382,414,382,415,414,382,383,415,383,416,415,383,384,416,384,417,416,384,385,417,385,418,417,385,386,418,386,419,418,386,387,419,387,420,419,387,388,420,388,421,420,388,389,421,389,422,421,389,390,422,390,423,422,390,391,423,391,424,423,391,392,424,392,425,424,392,393,425,393,426,425,393,394,426,394,427,426,394,395,427,395,428,427,396,397,429,397,430,429,397,398,430,398,431,430,398,399,431,399,432,431,399,400,432,400,433,432,400,401,433,401,434,433,401,402,434,402,435,434,402,403,435,403,436,435,403,404,436,404,437,436,404,405,437,405,438,437,405,406,438,406,439,438,406,407,439,407,440,439,407,408,440,408,441,440,408,409,441,409,442,441,409,410,442,410,443,442,410,411,443,411,444,443,411,412,444,412,445,444,412,413,445,413,446,445,413,414,446,414,447,446,414,415,447,415,448,447,415,416,448,416,449,448,416,417,449,417,450,449,417,418,450,418,451,450,418,419,451,419,452,451,419,420,452,420,453,452,420,421,453,421,454,453,421,422,454,422,455,454,422,423,455,423,456,455,423,424,456,424,457,456,424,425,457,425,458,457,425,426,458,426,459,458,426,427,459,427,460,459,427,428,460,428,461,460,429,430,462,430,463,462,430,431,463,431,464,463,431,432,464,432,465,464,432,433,465,433,466,465,433,434,466,434,467,466,434,435,467,435,468,467,435,436,468,436,469,468,436,437,469,437,470,469,437,438,470,438,471,470,438,439,471,439,472,471,439,440,472,440,473,472,440,441,473,441,474,473,441,442,474,442,475,474,442,443,475,443,476,475,443,444,476,444,477,476,444,445,477,445,478,477,445,446,478,446,479,478,446,447,479,447,480,479,447,448,480,448,481,480,448,449,481,449,482,481,449,450,482,450,483,482,450,451,483,451,484,483,451,452,484,452,485,484,452,453,485,453,486,485,453,454,486,454,487,486,454,455,487,455,488,487,455,456,488,456,489,488,456,457,489,457,490,489,457,458,490,458,491,490,458,459,491,459,492,491,459,460,492,460,493,492,460,461,493,461,494,493,462,463,495,463,496,495,463,464,496,464,497,496,464,465,497,465,498,497,465,466,498,466,499,498,466,467,499,467,500,499,467,468,500,468,501,500,468,469,501,469,502,501,469,470,502,470,503,502,470,471,503,471,504,503,471,472,504,472,505,504,472,473,505,473,506,505,473,474,506,474,507,506,474,475,507,475,508,507,475,476,508,476,509,508,476,477,509,477,510,509,477,478,510,478,511,510,478,479,511,479,512,511,479,480,512,480,513,512,480,481,513,481,514,513,481,482,514,482,515,514,482,483,515,483,516,515,483,484,516,484,517,516,484,485,517,485,518,517,485,486,518,486,519,518,486,487,519,487,520,519,487,488,520,488,521,520,488,489,521,489,522,521,489,490,522,490,523,522,490,491,523,491,524,523,491,492,524,492,525,524,492,493,525,493,526,525,493,494,526,494,527,526,495,496,528,496,529,528,496,497,529,497,530,529,497,498,530,498,531,530,498,499,531,499,532,531,499,500,532,500,533,532,500,501,533,501,534,533,501,502,534,502,535,534,502,503,535,503,536,535,503,504,536,504,537,536,504,505,537,505,538,537,505,506,538,506,539,538,506,507,539,507,540,539,507,508,540,508,541,540,508,509,541,509,542,541,509,510,542,510,543,542,510,511,543,511,544,543,511,512,544,512,545,544,512,513,545,513,546,545,513,514,546,514,547,546,514,515,547,515,548,547,515,516,548,516,549,548,516,517,549,517,550,549,517,518,550,518,551,550,518,519,551,519,552,551,519,520,552,520,553,552,520,521,553,521,554,553,521,522,554,522,555,554,522,523,555,523,556,555,523,524,556,524,557,556,524,525,557,525,558,557,525,526,558,526,559,558,526,527,559,527,560,559]},"mirror_p":{"type":"vec3","data":[[-4,-2,0],[4,-2,0],[4,2,0],[-4,2,0]]},"mirror_n":{"type":"vec3","data":[[0,0,1],[0,0,1],[0,0,1],[0,0,1]]},"mirror_i":{"type":"u32","data":[0,1,2,0,2,3]}},"geometry":{"sphere":{"attributes":{"POSITION":"p","NORMAL":"n"},"indices":"i"},"mirror":{"attributes":{"POSITION":"mirror_p","NORMAL":"mirror_n"},"indices":"mirror_i"}},"materials":{"mirror":{"inputs":{"base_color":[1,1,1],"base_metalness":1,"specular_roughness":0}},"coat":{"inputs":{"base_color":[0.5,0.08,0.025],"specular_roughness":0.6,"coat_weight":1,"coat_roughness":0.12}},"fuzz":{"inputs":{"base_color":[0.015,0.08,0.12],"specular_roughness":0.7,"fuzz_weight":1,"fuzz_color":[0.2,0.8,1],"fuzz_roughness":0.6}}},"nodes":[{"type":"camera","name":"camera","translation":[0,0,1],"material":{"program":"std/camera","inputs":{"projection":"ortho","ortho_scale":5.5}}},{"type":"mesh","name":"mirror","geometry":"mirror","materials":["mirror"]},{"type":"mesh","name":"coat","geometry":"sphere","materials":["coat"],"translation":[-1.15,0,4]},{"type":"mesh","name":"fuzz","geometry":"sphere","materials":["fuzz"],"translation":[1.15,0,4]},{"type":"light","shape":"sun","energy":2,"angle":0.15,"rotation":[0,1,0,0],"shadowed_by":[]},{"type":"light","shape":"environment","color":[0.2,0.2,0.2]}],"render":{"resolution":[480,240],"display": {"program":"std/standard","inputs":{"dither_intensity":0}},"background":[0,0,0]}}diff --git a/crates/vork-render/tests/fixtures/imported-camera.gltf b/crates/vork-render/tests/fixtures/imported-camera.gltfnew file mode 100644index 0000000..d52634f--- /dev/null+++ b/crates/vork-render/tests/fixtures/imported-camera.gltf@@ -0,0 +1 @@+{"asset":{"version":"2.0"},"scene":0,"scenes":[{"nodes":[0]}],"nodes":[{"name":"parent","translation":[2,3,4],"children":[1,2]},{"name":"shot","camera":0,"translation":[0,0,5]},{"camera":1}],"cameras":[{"type":"perspective","perspective":{"yfov":1,"znear":0.2,"zfar":50}},{"type":"orthographic","orthographic":{"xmag":3,"ymag":2,"znear":0.1,"zfar":40}}]}diff --git a/crates/vork-render/tests/fixtures/sampled-hit-energy.json b/crates/vork-render/tests/fixtures/sampled-hit-energy.jsonnew file mode 100644index 0000000..bbbe0c5--- /dev/null+++ b/crates/vork-render/tests/fixtures/sampled-hit-energy.json@@ -0,0 +1,175 @@+{+ "version": 2,+ "render": {+ "resolution": [+ 16,+ 16+ ],+ "background": [+ 0,+ 0,+ 0+ ]+ },+ "buffers": {+ "p": {+ "type": "vec3",+ "data": [+ [+ -2,+ -2,+ 0+ ],+ [+ 2,+ -2,+ 0+ ],+ [+ 2,+ 2,+ 0+ ],+ [+ -2,+ 2,+ 0+ ]+ ]+ },+ "n": {+ "type": "vec3",+ "data": [+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ]+ ]+ },+ "i": {+ "type": "u32",+ "data": [+ 0,+ 1,+ 2,+ 0,+ 2,+ 3+ ]+ }+ },+ "geometry": {+ "quad": {+ "attributes": {+ "POSITION": "p",+ "NORMAL": "n"+ },+ "indices": "i"+ }+ },+ "programs": {+ "receiver": {+ "source": "struct Inputs {}; Closure surface(ShadingContext ctx,Inputs i) {Closure c={}; c.base_color=float3(0.7); c.specular_roughness=1.; c.subsurface_weight=1.; c.subsurface_color=float3(0.8); c.geometry_thin_walled=true; return c;}"+ }+ },+ "materials": {+ "receiver": {+ "program": "receiver"+ },+ "mirror": {+ "inputs": {+ "base_color": [+ 1,+ 1,+ 1+ ],+ "base_metalness": 1,+ "specular_roughness": 0+ }+ }+ },+ "nodes": [+ {+ "type": "camera",+ "translation": [+ 0,+ 0,+ 3+ ],+ "material": {+ "program": "std/camera",+ "inputs": {+ "projection": "ortho",+ "ortho_scale": 0.2+ }+ }+ },+ {+ "type": "mesh",+ "geometry": "quad",+ "materials": [+ "mirror"+ ],+ "scale": [+ 0.06,+ 0.06,+ 1+ ]+ },+ {+ "type": "mesh",+ "geometry": "quad",+ "materials": [+ "receiver"+ ],+ "translation": [+ 0,+ 0,+ 4+ ],+ "rotation": [+ 0,+ 1,+ 0,+ 0+ ]+ },+ {+ "type": "light",+ "shape": "rectangle",+ "size": 2,+ "size_y": 2,+ "energy": 10,+ "translation": [+ 0,+ 0,+ 6+ ]+ },+ {+ "type": "light",+ "shape": "environment",+ "color": [+ 0,+ 0,+ 0+ ]+ }+ ]+}diff --git a/crates/vork-render/tests/fixtures/tiny-reflection-emitter.json b/crates/vork-render/tests/fixtures/tiny-reflection-emitter.jsonnew file mode 100644index 0000000..e5d1ab3--- /dev/null+++ b/crates/vork-render/tests/fixtures/tiny-reflection-emitter.json@@ -0,0 +1,13 @@+{+ "version": 2,+ "materials": {+ "floor": {"inputs": {"base_color": [0, 0, 0], "specular_roughness": 0.4}},+ "source": {"inputs": {"base_color": [0, 0, 0], "specular_weight": 0, "emission_color": [1, 1, 1], "emission_luminance": 3000}}+ },+ "nodes": [+ {"type": "mesh", "name": "floor", "geometry": {"std": "grid", "size": [20, 20]}, "materials": ["floor"]},+ {"type": "mesh", "name": "source", "geometry": {"std": "grid", "size": [0.02, 0.02]}, "materials": ["source"], "translation": [0, 2, -4], "rotation": [1, 0, 0, 0]},+ {"type":"camera","name":"camera","translation":[0,2,4],"target":[0,0,0],"material":{"program":"std/camera","inputs":{"lens":50}}}+ ],+ "render": {"resolution": [32, 24], "background": [0, 0, 0]}+}diff --git a/crates/vork-render/tests/fixtures/volume-glass-box.json b/crates/vork-render/tests/fixtures/volume-glass-box.jsonnew file mode 100644index 0000000..da95e6b--- /dev/null+++ b/crates/vork-render/tests/fixtures/volume-glass-box.json@@ -0,0 +1,190 @@+{+ "version": 2,+ "render": {+ "background": "environment",+ "display": {"program":"std/agx","inputs":{"exposure":0}},+ "resolution": [+ 480,+ 320+ ],+ "fps": 12,+ "duration": 1,+ "camera": "shot_camera"+ },+ "nodes": [+ {+ "type": "mesh",+ "name": "ground",+ "scale": [14,1,14],+ "children": [],+ "geometry": "unit_plane",+ "materials": [+ "ground_surface"+ ]+ },+ {+ "type": "mesh",+ "name": "display_box",+ "translation": [-2,0.5,0],+ "children": [],+ "geometry": "unit_box",+ "materials": [+ "display_box_surface"+ ]+ },+ {"type":"camera","translation":[7,5,10],"rotation":[-0.16074243187904358,0.2963387072086334,0.050669584423303604,0.9400945901870728],"name":"shot_camera","children":[],"material":{"program":"std/camera","inputs":{"lens":30.049168798152053,"clip_start":0.1,"clip_end":100,"projection":"persp"}}},+ {"type":"light","translation":[-3,5,4],"rotation":[-0.31402075687864384,-0.2984014753183226,-0.10467358562621462,0.895204425954968],"color":[1,1,1],"shape":"rectangle","name":"key","children":[],"visible_glossy":false,"energy":900,"size":4,"size_y":4},+ {"type":"light","translation":[4,3,2],"rotation":[-0.17754884951811015,0.5141519822026013,0.10973122366563245,0.8319153825869399],"color":[1,1,1],"shape":"rectangle","name":"fill","children":[],"visible_diffuse":false,"energy":350,"size":3,"size_y":4},+ {"type":"light","translation":[0,4,-4],"rotation":[0,0.9486832980505138,0.31622776601683794,0],"color":[1,1,1],"shape":"rectangle","name":"rim","children":[],"visible_diffuse":false,"energy":650,"size":3,"size_y":2},+ {+ "type": "light",+ "name": "environment",+ "shape": "environment",+ "color": [+ 0.12,+ 0.12,+ 0.12+ ]+ },+ {+ "type": "mesh",+ "name": "room_back",+ "geometry": "unit_box",+ "materials": [+ "room"+ ],+ "translation": [0,2,-3],+ "scale": [10,4,0.15]+ },+ {+ "type": "mesh",+ "name": "room_side",+ "geometry": "unit_box",+ "materials": [+ "room"+ ],+ "translation": [-4,2,0],+ "scale": [0.15,4,6]+ },+ {+ "type": "mesh",+ "name": "fog_glass_box",+ "geometry": "unit_box",+ "materials": [+ "smoke"+ ],+ "translation": [0,1.5,0],+ "scale": [3,3,3]+ }+ ],+ "buffers": {+ "unit_plane_position": {+ "type": "vec3",+ "offset": 912,+ "count": 4,+ "file": "../../../../examples/assets/starter-geometry.bin"+ },+ "unit_plane_normal": {+ "type": "vec3",+ "offset": 960,+ "count": 4,+ "file": "../../../../examples/assets/starter-geometry.bin"+ },+ "unit_plane_uv0": {+ "type": "vec2",+ "offset": 1008,+ "count": 4,+ "file": "../../../../examples/assets/starter-geometry.bin"+ },+ "unit_plane_indices": {+ "type": "u32",+ "offset": 1040,+ "count": 6,+ "file": "../../../../examples/assets/starter-geometry.bin"+ },+ "unit_box_position": {+ "type": "vec3",+ "offset": 0,+ "count": 24,+ "file": "../../../../examples/assets/starter-geometry.bin"+ },+ "unit_box_normal": {+ "type": "vec3",+ "offset": 288,+ "count": 24,+ "file": "../../../../examples/assets/starter-geometry.bin"+ },+ "unit_box_uv0": {+ "type": "vec2",+ "offset": 576,+ "count": 24,+ "file": "../../../../examples/assets/starter-geometry.bin"+ },+ "unit_box_indices": {+ "type": "u32",+ "offset": 768,+ "count": 36,+ "file": "../../../../examples/assets/starter-geometry.bin"+ }+ },+ "geometry": {+ "unit_plane": {+ "topology": "triangles",+ "attributes": {+ "POSITION": "unit_plane_position",+ "NORMAL": "unit_plane_normal",+ "TEXCOORD_0": "unit_plane_uv0"+ },+ "indices": "unit_plane_indices"+ },+ "unit_box": {+ "topology": "triangles",+ "attributes": {+ "POSITION": "unit_box_position",+ "NORMAL": "unit_box_normal",+ "TEXCOORD_0": "unit_box_uv0"+ },+ "indices": "unit_box_indices"+ }+ },+ "materials": {+ "ground_surface": {+ "inputs": {+ "base_color": [+ 0.35,+ 0.35,+ 0.35+ ],+ "specular_roughness": 0.8+ }+ },+ "display_box_surface": {+ "inputs": {+ "base_color": [+ 0.18,+ 0.18,+ 0.18+ ],+ "base_metalness": 0,+ "specular_roughness": 0.45+ }+ },+ "room": {+ "inputs": {+ "base_color": [+ 0.32,+ 0.34,+ 0.38+ ],+ "specular_roughness": 0.8+ }+ },+ "smoke": {+ "program": "glass_fog",+ "inputs": {"density":0.55,"scattering":[0.65,0.8,1],"absorption":[0.35000002,0.19999999,0],"anisotropy":0.2}+ }+ },+ "programs": {+ "glass_fog": {"file": "../../../../scenes/programs/glass-fog.slang"}+ }+}diff --git a/crates/vork-render/tests/goldens/skinned-box.gltf b/crates/vork-render/tests/goldens/skinned-box.gltfnew file mode 100644index 0000000..28c2821--- /dev/null+++ b/crates/vork-render/tests/goldens/skinned-box.gltf@@ -0,0 +1,183 @@+{+ "asset": {+ "version": "2.0"+ },+ "buffers": [+ {+ "uri": "data:application/octet-stream;base64,AAAAPwAAAL8AAAC/AAAAPwAAAD8AAAC/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAC/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAL8AAAC/AAAAvwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAA/AAAAvwAAAD8AAAC/AAAAvwAAAD8AAAC/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAvwAAAD8AAAC/AAAAPwAAAD8AAAA/AAAAPwAAAD8AAAC/AAAAvwAAAL8AAAC/AAAAPwAAAL8AAAC/AAAAPwAAAL8AAAA/AAAAvwAAAL8AAAC/AAAAPwAAAL8AAAA/AAAAvwAAAL8AAAA/AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAA/AAAAPwAAAD8AAAA/AAAAvwAAAL8AAAA/AAAAPwAAAD8AAAA/AAAAvwAAAD8AAAA/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAPwAAAD8AAAC/AAAAvwAAAL8AAAC/AAAAPwAAAD8AAAC/AAAAPwAAAL8AAAC/AACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAAAAAAIA/MzMzvwAAAAAAAAAAMzMzP5qZGT8AAAAA",+ "byteLength": 1824+ }+ ],+ "bufferViews": [+ {+ "buffer": 0,+ "byteOffset": 0,+ "byteLength": 432+ },+ {+ "buffer": 0,+ "byteOffset": 432,+ "byteLength": 432+ },+ {+ "buffer": 0,+ "byteOffset": 864,+ "byteLength": 288+ },+ {+ "buffer": 0,+ "byteOffset": 1152,+ "byteLength": 576+ },+ {+ "buffer": 0,+ "byteOffset": 1728,+ "byteLength": 64+ },+ {+ "buffer": 0,+ "byteOffset": 1792,+ "byteLength": 8+ },+ {+ "buffer": 0,+ "byteOffset": 1800,+ "byteLength": 24+ }+ ],+ "accessors": [+ {+ "bufferView": 0,+ "componentType": 5126,+ "count": 36,+ "type": "VEC3",+ "min": [+ -0.5,+ -0.5,+ -0.5+ ],+ "max": [+ 0.5,+ 0.5,+ 0.5+ ]+ },+ {+ "bufferView": 1,+ "componentType": 5126,+ "count": 36,+ "type": "VEC3"+ },+ {+ "bufferView": 2,+ "componentType": 5123,+ "count": 36,+ "type": "VEC4"+ },+ {+ "bufferView": 3,+ "componentType": 5126,+ "count": 36,+ "type": "VEC4"+ },+ {+ "bufferView": 4,+ "componentType": 5126,+ "count": 1,+ "type": "MAT4"+ },+ {+ "bufferView": 5,+ "componentType": 5126,+ "count": 2,+ "type": "SCALAR",+ "min": [+ 0+ ],+ "max": [+ 1+ ]+ },+ {+ "bufferView": 6,+ "componentType": 5126,+ "count": 2,+ "type": "VEC3"+ }+ ],+ "materials": [+ {+ "pbrMetallicRoughness": {+ "baseColorFactor": [+ 0.2,+ 0.65,+ 0.9,+ 1+ ],+ "metallicFactor": 0,+ "roughnessFactor": 0.4+ }+ }+ ],+ "meshes": [+ {+ "primitives": [+ {+ "attributes": {+ "POSITION": 0,+ "NORMAL": 1,+ "JOINTS_0": 2,+ "WEIGHTS_0": 3+ },+ "material": 0+ }+ ]+ }+ ],+ "nodes": [+ {+ "mesh": 0,+ "skin": 0+ },+ {+ "name": "joint"+ }+ ],+ "skins": [+ {+ "joints": [+ 1+ ],+ "inverseBindMatrices": 4+ }+ ],+ "animations": [+ {+ "samplers": [+ {+ "input": 5,+ "output": 6,+ "interpolation": "LINEAR"+ }+ ],+ "channels": [+ {+ "sampler": 0,+ "target": {+ "node": 1,+ "path": "translation"+ }+ }+ ]+ }+ ],+ "scenes": [+ {+ "nodes": [+ 0,+ 1+ ]+ }+ ],+ "scene": 0+}diff --git a/crates/vork-render/tests/presets/analytic-7fefd52a.json b/crates/vork-render/tests/presets/analytic-7fefd52a.jsonnew file mode 100644index 0000000..d09de78--- /dev/null+++ b/crates/vork-render/tests/presets/analytic-7fefd52a.json@@ -0,0 +1,3 @@+{+ "fast_gi": {}+}diff --git a/crates/vork-render/tests/presets/fibre-receiver-2172aaaf.json b/crates/vork-render/tests/presets/fibre-receiver-2172aaaf.jsonnew file mode 100644index 0000000..b8feabf--- /dev/null+++ b/crates/vork-render/tests/presets/fibre-receiver-2172aaaf.json@@ -0,0 +1,4 @@+{+ "samples": 2,+ "reflections": "environment"+}diff --git a/crates/vork-render/tests/presets/hit-layers-3bd1f7c2.json b/crates/vork-render/tests/presets/hit-layers-3bd1f7c2.jsonnew file mode 100644index 0000000..5f60423--- /dev/null+++ b/crates/vork-render/tests/presets/hit-layers-3bd1f7c2.json@@ -0,0 +1,4 @@+{+ "samples": 32,+ "reflections": "ray"+}diff --git a/crates/vork-render/tests/presets/jitter-aa-f8d98a5b.json b/crates/vork-render/tests/presets/jitter-aa-f8d98a5b.jsonnew file mode 100644index 0000000..ed5655a--- /dev/null+++ b/crates/vork-render/tests/presets/jitter-aa-f8d98a5b.json@@ -0,0 +1,4 @@+{+ "samples": 8,+ "fast_gi": {}+}diff --git a/crates/vork-render/tests/presets/mesh-thickness-943f9677.json b/crates/vork-render/tests/presets/mesh-thickness-943f9677.jsonnew file mode 100644index 0000000..dfeb01e--- /dev/null+++ b/crates/vork-render/tests/presets/mesh-thickness-943f9677.json@@ -0,0 +1,4 @@+{+ "refraction": "ray",+ "reflections": "environment"+}diff --git a/crates/vork-render/tests/presets/program-transparency-874d5753.json b/crates/vork-render/tests/presets/program-transparency-874d5753.jsonnew file mode 100644index 0000000..ed5655a--- /dev/null+++ b/crates/vork-render/tests/presets/program-transparency-874d5753.json@@ -0,0 +1,4 @@+{+ "samples": 8,+ "fast_gi": {}+}diff --git a/crates/vork-render/tests/presets/ray-offscreen-c085ab7c.json b/crates/vork-render/tests/presets/ray-offscreen-c085ab7c.jsonnew file mode 100644index 0000000..1fa6b13--- /dev/null+++ b/crates/vork-render/tests/presets/ray-offscreen-c085ab7c.json@@ -0,0 +1,5 @@+{+ "samples": 4,+ "reflections": "ray",+ "refraction": "ray"+}diff --git a/crates/vork-render/tests/presets/subsurface-mix-676a8348.json b/crates/vork-render/tests/presets/subsurface-mix-676a8348.jsonnew file mode 100644index 0000000..b0bf876--- /dev/null+++ b/crates/vork-render/tests/presets/subsurface-mix-676a8348.json@@ -0,0 +1,4 @@+{+ "reflections": "environment",+ "shadow_method": "ray"+}diff --git a/crates/vork-render/tests/presets/tiny-reflection-emitter-25918a49.json b/crates/vork-render/tests/presets/tiny-reflection-emitter-25918a49.jsonnew file mode 100644index 0000000..108da15--- /dev/null+++ b/crates/vork-render/tests/presets/tiny-reflection-emitter-25918a49.json@@ -0,0 +1,6 @@+{+ "samples": 64,+ "reflections": "ray",+ "refraction": "environment",+ "fast_gi": null+}diff --git a/crates/vork-render/tests/presets/volume-glass-box-c5ca7d6d.json b/crates/vork-render/tests/presets/volume-glass-box-c5ca7d6d.jsonnew file mode 100644index 0000000..dbd65ad--- /dev/null+++ b/crates/vork-render/tests/presets/volume-glass-box-c5ca7d6d.json@@ -0,0 +1,6 @@+{+ "samples": 4,+ "fast_gi": {+ "method": "auto"+ }+}diff --git a/crates/vork-render/tests/support/mod.rs b/crates/vork-render/tests/support/mod.rsnew file mode 100644index 0000000..86c2555--- /dev/null+++ b/crates/vork-render/tests/support/mod.rs@@ -0,0 +1,30 @@+// Custom Hair transport tests retain both closure responses independently of+// std/hair's physical scattering.+pub fn with_test_hair(mut scene: serde_json::Value) -> serde_json::Value {+ scene["programs"]["test_hair"] = serde_json::json!({"source": include_str!("../fixtures/hair-model.slang")});+ scene+}++/// Expand unit-box test fixtures without invoking the authored std preprocessor.+#[allow(dead_code)]+pub fn with_box_geometry(mut scene:serde_json::Value)->serde_json::Value {+ let fixture:serde_json::Value=serde_json::from_str(include_str!("../fixtures/analytic.json")).unwrap();+ let mut geometry=fixture["geometry"]["shape_box"].clone();+ for name in geometry["attributes"].as_object_mut().unwrap().values_mut() {*name=name.as_str().unwrap().replace("shape_box_","test_unit_box_").into();}+ geometry["indices"]=serde_json::json!("test_unit_box_indices");+ scene["geometry"]["test_unit_box"]=geometry;+ for (name,buffer) in fixture["buffers"].as_object().unwrap() {+ if name.starts_with("shape_box_") {scene["buffers"][name.replace("shape_box_","test_unit_box_")]=buffer.clone();}+ }+ fn nodes(value:&mut serde_json::Value) {+ for node in value.as_array_mut().into_iter().flatten() {+ if node["geometry"]["std"]=="box" {+ let size=node["geometry"]["size"].clone();+ let scale:Vec<_>=(0..3).map(|i|size[i].as_f64().unwrap()*node["scale"][i].as_f64().unwrap_or(1.)).collect();+ node["geometry"]=serde_json::json!("test_unit_box");node["scale"]=serde_json::json!(scale);+ }+ if let Some(children)=node.get_mut("children") {nodes(children);}+ }+ }+ nodes(&mut scene["nodes"]);scene+}diff --git a/crates/vork-scene/build.rs b/crates/vork-scene/build.rsindex 129bd88..c51aeff 100644--- a/crates/vork-scene/build.rs+++ b/crates/vork-scene/build.rs@@ -2,11 +2,11 @@use std::{env, fmt::Write, fs, path::Path};fn main() {- // The private corpus and its test modules are intentionally absent from public exports.+ // Explicit opt-in: directory layout must not change test admission.println!("cargo:rustc-check-cfg=cfg(vork_private_tests)");println!("cargo:rerun-if-changed=build.rs");- if std::path::Path::new("../../scenes").is_dir() {- println!("cargo:rerun-if-changed=../../scenes");+ println!("cargo:rerun-if-env-changed=VORK_PRIVATE_TESTS");+ if std::env::var("VORK_PRIVATE_TESTS").as_deref() == Ok("1") {println!("cargo:rustc-cfg=vork_private_tests");}let source = "openpbr-params.md";diff --git a/crates/vork-scene/src/libraries.rs b/crates/vork-scene/src/libraries.rsindex 676ee7c..e7916c2 100644--- a/crates/vork-scene/src/libraries.rs+++ b/crates/vork-scene/src/libraries.rs@@ -48,9 +48,9 @@ pub const LIBRARIES: &[Library] = &[help: include_str!("../../../libraries/std/HELP.txt"),modules: modules!("std":"openpbr_core" false, "texture" false, "normal_filter" false, "hair" true, "hair_bsdf" false,- "camera" true, "fog" true, "sky" true, "environment_image" true, "grid" false, "pnanovdb" false, "vector" false,+ "camera" true, "sky" true, "environment_image" true, "grid" false, "pnanovdb" false, "vector" false,"color" false, "procedurals" false, "particles" false,- "highlight" false, "bloom" true, "agx" true, "standard" true, "display" false),+ "bloom" true, "agx" true, "standard" true, "display" false),profiles: &[("std/previs", include_str!("../../../libraries/std/profiles/previs.json")),("std/draft", include_str!("../../../libraries/std/profiles/draft.json")),@@ -64,7 +64,7 @@ pub const LIBRARIES: &[Library] = &[name: "blender",help: include_str!("../../../libraries/blender/HELP.txt"),modules: modules!("blender":- "principled_volume" true, "volume" false, "nodes" false,+ "nodes" false,"texture_coordinate" false, "color" false, "procedurals" false, "filmic" true, "display_lut" false),profiles: &[],images: &[("blender/filmic", "lut", ProgramImage::File("libraries/blender/filmic.exr"))],@@ -80,7 +80,7 @@ pub const LIBRARIES: &[Library] = &[Library {name: "post",help: include_str!("../../../libraries/post/HELP.txt"),- modules: modules!("post": "glare" true, "vignette" true, "lens_distortion" true, "white_balance" true),+ modules: modules!("post": "white_balance" true),profiles: &[],images: &[],},@@ -112,7 +112,7 @@ pub fn library(name: &str) -> Option<&'static Library> {}/// Every bundled module of every library.pub fn modules() -> impl Iterator<Item = &'static Module> {- LIBRARIES.iter().flat_map(|library| library.modules)+ LIBRARIES.iter().flat_map(|library| library.modules).chain(test_modules())}pub fn module_source(name: &str) -> Option<&'static str> {modules().find(|module| module.name == name).map(|module| module.source)@@ -126,3 +126,16 @@ pub fn program_image(program: &str, input: &str) -> Option<ProgramImage> {pub fn material_programs<'a>() -> impl Iterator<Item = &'a str> {std::iter::once("std/openpbr").chain(modules().filter(|module| module.material).map(|module| module.name))}++// Disabled release conveniences remain available only to internal media tests.+fn test_modules() -> impl Iterator<Item = &'static Module> {+ #[cfg(feature = "test-support")]+ let modules = modules!("std": "fog" true);+ #[cfg(not(feature = "test-support"))]+ let modules: &[Module] = &[];+ #[cfg(feature = "test-support")]+ let blender = modules!("blender": "principled_volume" true, "volume" false);+ #[cfg(not(feature = "test-support"))]+ let blender: &[Module] = &[];+ modules.iter().chain(blender)+}diff --git a/crates/vork-scene/src/v2/diagnostics.rs b/crates/vork-scene/src/v2/diagnostics.rsindex a22d7e9..c3cf23d 100644--- a/crates/vork-scene/src/v2/diagnostics.rs+++ b/crates/vork-scene/src/v2/diagnostics.rs@@ -36,7 +36,7 @@ pub fn unknown<'a>(kind: &str, name: &str, valid: impl IntoIterator<Item = &'a s("value", "Filmic", "render.display with the blender/filmic display program"),("value", "ORTHO", "ortho (lowercase)"),("field", "extension", "wrap_s/wrap_t on the image"),- ("token", "bloom", "std/bloom instead of post/glare type bloom"),+ ("token", "bloom", "std/bloom"),("program", "blender/principled", "std/openpbr"),];if let Some((_, _, hint)) = BLENDER_HINTS.iter().find(|(k, n, _)| *k == kind && *n == name) {@@ -631,7 +631,7 @@ mod blender_hints {("value", "Filmic", "AgX", "blender/filmic"),("value", "ORTHO", "ortho", "ortho (lowercase)"),("field", "extension", "wrap_s", "wrap_s/wrap_t"),- ("token", "bloom", "fog_glow", "std/bloom instead of post/glare type bloom"),+ ("token", "bloom", "fog_glow", "std/bloom"),] {let error = unknown(kind, name, [valid]);assert!(error.contains(expected), "{error}");diff --git a/crates/vork-scene/src/v2/inline.rs b/crates/vork-scene/src/v2/inline.rsindex 7499afe..b91ec3f 100644--- a/crates/vork-scene/src/v2/inline.rs+++ b/crates/vork-scene/src/v2/inline.rs@@ -154,7 +154,7 @@ mod tests {"version":2,"nodes":[{"type":"camera","name":"camera"}],"render":{"display":{"program":"blender/filmic","inputs":{"lut":{"image":{"render":{"camera":"camera","compositor":[{- "program":"post/glare","inputs":{"texture":{"image":{"file":"lut.exr"}}}+ "program":"post/white_balance","inputs":{"texture":{"image":{"file":"lut.exr"}}}}]}}}}}}})).unwrap()).unwrap();@@ -180,20 +180,20 @@ mod tests {#[test]fn inline_render_images_lower_their_compositors_recursively() {let image = serde_json::json!({"render":{"camera":"capture","root":"empty",- "compositor":[{"program":"post/glare"}]}});+ "compositor":[{"program":"post/white_balance"}]}});for document in [serde_json::json!({"version":2,"nodes":[{"type":"camera","name":"capture"},{"type":"node","name":"empty"}],"materials":{"surface":{"inputs":{"base_color":{"image":image}}}}}),serde_json::json!({"version":2,"nodes":[{"type":"camera","name":"capture"},{"type":"node","name":"empty"},{"type":"light","shape":"environment","material":{"program":"std/environment_image","inputs":{"image":{"image":image}}}}]}),serde_json::json!({"version":2,"nodes":[{"type":"camera","name":"capture"},{"type":"node","name":"empty"}],- "render":{"compositor":[{"program":"post/glare","inputs":{"texture":{"image":image}}}]}}),+ "render":{"compositor":[{"program":"post/white_balance","inputs":{"texture":{"image":image}}}]}}),] {let loaded = Scene::from_json(&serde_json::to_vec(&document).unwrap());let scene=loaded.unwrap();let image = scene.images.values().next().unwrap().render.as_ref().unwrap();assert_eq!(image.compositor.len(), 1);- assert_eq!(scene.materials[image.compositor[0].material()].program, "post/glare");+ assert_eq!(scene.materials[image.compositor[0].material()].program, "post/white_balance");}}#[test]diff --git a/crates/vork-scene/src/v2/mod.rs b/crates/vork-scene/src/v2/mod.rsindex e90c09d..1471257 100644--- a/crates/vork-scene/src/v2/mod.rs+++ b/crates/vork-scene/src/v2/mod.rs@@ -42,6 +42,10 @@ pub enum NameOr<T> {#[serde(deny_unknown_fields)]#[schemars(extend("x-help-extra" = "coordinates: glTF right-handed Y-up; cameras look along local -Z"))]pub struct Scene {+ /// Editor JSON Schema address; metadata only, never fetched by the renderer.+ #[serde(rename = "$schema", default, skip_serializing_if = "Option::is_none")]+ #[schemars(extend("x-help-path" = "scene.$schema", "x-help" = "string; editor schema URL"))]+ pub schema: Option<String>,/// Internal release normalization; never scene content.#[serde(skip)]pub media_disabled: bool,@@ -245,6 +249,15 @@ pub(super) fn validate_name(s: &str) -> Result<()> {#[cfg(test)]mod tests {use super::*;+ #[test]+ fn editor_schema_is_optional_metadata() {+ let input = serde_json::json!({"version": 2, "nodes": [], "$schema": "https://voyager.so/vork/schema/scene.schema.json"});+ let scene: Scene = serde_json::from_value(input).unwrap();+ assert_eq!(scene.schema.as_deref(), Some("https://voyager.so/vork/schema/scene.schema.json"));+ assert_eq!(serde_json::to_value(scene).unwrap()["$schema"], "https://voyager.so/vork/schema/scene.schema.json");+ assert!(serde_json::from_value::<Scene>(serde_json::json!({"version": 2, "nodes": [], "$schem": "typo"})).is_err());+ }+#[test]fn propagation_is_only_program_and_ordered_bounds() {let scene=serde_json::json!({"version":2,"nodes":[{"type":"camera"}],@@ -391,7 +404,7 @@ mod tests {assert!(error.contains("unknown program \"blender/principled\"")&& error.contains("use std/openpbr"), "{error}");assert!(crate::libraries::module_source("blender/principled").is_none());- assert!(crate::libraries::module_source("blender/principled_volume").is_some());+ assert_eq!(crate::libraries::module_source("blender/principled_volume").is_some(), cfg!(feature="test-support"));}#[test]fn camera_material_uses_shared_inline_material() {@@ -539,7 +552,7 @@ mod light_link_tests {mod launch_api_tests {#[test]fn legacy_world_medium_decodes_but_is_not_an_api_field() {- let scene=super::Scene::from_json(br#"{"version":2,"nodes":[{"type":"camera"},{"type":"light","shape":"environment","medium":{"program":"std/fog"}}]}"#).unwrap();+ let scene=super::Scene::from_json(br#"{"version":2,"nodes":[{"type":"camera"},{"type":"light","shape":"environment","medium":{"program":{"source":"struct Inputs {}; MediumCoefficients medium(MediumContext c, Inputs i) { return MediumCoefficients(); }"}}}]}"#).unwrap();assert!(matches!(&scene.nodes[1].kind,super::NodeKind::Light {medium:Some(_),..}));let schema=super::schema().to_value().to_string();assert!(!schema.contains("light.medium"));diff --git a/crates/vork-scene/src/v2/node.rs b/crates/vork-scene/src/v2/node.rsindex efc274f..fe2f960 100644--- a/crates/vork-scene/src/v2/node.rs+++ b/crates/vork-scene/src/v2/node.rs@@ -7,7 +7,7 @@ pub struct Node {/// glTF node TRS, written directly on the node (`translation`, `rotation`, `scale`).#[serde(default, flatten)]pub transform: Transform,- #[schemars(extend("x-source" = "Blender Track To constraint (vork target shorthand)", "x-help-path" = "node.target", "x-help" = "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top"))]+ #[schemars(extend("x-source" = "Blender Track To constraint (vork target shorthand)", "x-help-path" = "node.target", "x-help" = "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translation"))]pub target: Option<AimTarget>,#[serde(default)]#[schemars(extend("x-source" = "vork (explicit contract/technique choice)", "x-help-path" = "node.children", "x-help" = "node[]"))]@@ -93,7 +93,7 @@ pub enum NodeKind {#[schemars(with = "NameOr<Geometry>")]geometry: String,#[serde(default)]- #[schemars(extend("x-source" = "vork (explicit contract/technique choice)", "x-help-path" = "node.mesh.materials", "x-help" = "(material-name|inline material)[]; empty = default std/openpbr with roughness 0.5"))]+ #[schemars(extend("x-source" = "OpenPBR Surface 1.1.1", "x-help-path" = "node.mesh.materials", "x-help" = "(material-name|inline material)[]; empty = default std/openpbr with roughness 0.3"))]#[schemars(with = "Vec<NameOr<Material>>")]materials: Vec<String>,#[schemars(extend("x-source" = "vork (explicit contract/technique choice)", "x-help-path" = "node.mesh.instances", "x-help" = "instances|null"))]diff --git a/crates/vork-scene/src/v2/reference.txt b/crates/vork-scene/src/v2/reference.txtindex e0b8564..2b47dc6 100644--- a/crates/vork-scene/src/v2/reference.txt+++ b/crates/vork-scene/src/v2/reference.txt@@ -135,7 +135,7 @@ node.geometry (mesh): geometry-name|inline geometrynode.instances (mesh): instances|nullnode.instances.attributes (mesh): equal-length buffers: TRANSLATION vec3, ROTATION vec4 (xyzw), SCALE vec3 (omitted = identity; any zero world-scale component hides the instance), time_offset f32, pass_index u32, custom columns bind to material inputsnode.instances.count (mesh): one-element u32 compute buffer; zero to attribute capacity; overflow rejects the exposure-node.materials (mesh): (material-name|inline material)[]; empty = default std/openpbr with roughness 0.5; default []+node.materials (mesh): (material-name|inline material)[]; empty = default std/openpbr with roughness 0.3; default []node.morph_weights (mesh): {name:number}; default {}node.skin (mesh): skin|nullnode.skin.inverse_bind_matrices (mesh): mat4-buffer-name|inline buffer@@ -144,7 +144,7 @@ node.name: string; globally unique, including imported nodes; default ""node.pass_index: u32|null; 1..65535; object IDnode.rotation: [x,y,z,w] quaternion | {euler:[x,y,z]} (Blender XYZ); default [0,0,0,1]node.scale: [x,y,z]; any zero world-scale component hides geometry, including children; default [1,1,1]-node.target: node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top+node.target: node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translationnode.translation: [x,y,z]; parent frame; default [0,0,0]node.visible: bool; false hides the subtree and disables its lights; animatable (step); default truenode.visible_camera: bool; default true@@ -176,6 +176,7 @@ render.motion_blur.position: start|center|end; default centerrender.motion_blur.shutter: number; frames; default 0.5render.resolution: uvec2; default [1920,1080]render.root: node-name|null; only this subtree draws and is lit; objects outside still cast shadows; null = whole scene; default null+scene.$schema: string; editor schema URLscene.animation: layer[]; default []scene.buffers: {name:buffer}; default {}scene.geometry: {name:geometry}; default {}diff --git a/crates/vork-scene/src/v2/render.rs b/crates/vork-scene/src/v2/render.rsindex 5b187aa..0912817 100644--- a/crates/vork-scene/src/v2/render.rs+++ b/crates/vork-scene/src/v2/render.rs@@ -571,7 +571,7 @@ mod compositor_tests {assert!(serde_json::from_str::<Render>(r#"{"glare":{}}"#).is_err());let mut scene: Scene = serde_json::from_value(serde_json::json!({"version":2,"nodes":[{"type":"camera"}],- "materials":{"bloom":{"program":"std/bloom","inputs":{"original":{"channel":"color"},"source":{"channel":"color"}}},"grade":{"program":"post/lens_distortion"}},+ "materials":{"bloom":{"program":"std/bloom","inputs":{"original":{"channel":"color"},"source":{"channel":"color"}}},"grade":{"program":"post/white_balance"}},"render":{"compositor":["bloom","grade"]}})).unwrap();scene.validate().unwrap();diff --git a/crates/vork-scene/src/v2/schema.rs b/crates/vork-scene/src/v2/schema.rsindex 66df808..f8980b6 100644--- a/crates/vork-scene/src/v2/schema.rs+++ b/crates/vork-scene/src/v2/schema.rs@@ -5,6 +5,7 @@ pub(super) fn authored_schema() -> schemars::Schema {.for_deserialize().into_generator().into_root_schema_for::<super::Scene>();+ schema.as_object_mut().unwrap().insert("$id".into(), serde_json::json!("https://voyager.so/vork/schema/scene.schema.json"));schema.get_mut("properties").unwrap()["version"]["const"] = serde_json::json!(2);schema.as_object_mut().unwrap().insert("x-standards".into(),diff --git a/crates/vork-scene/src/v2/targets.rs b/crates/vork-scene/src/v2/targets.rsindex 5d27deb..7b6ac8a 100644--- a/crates/vork-scene/src/v2/targets.rs+++ b/crates/vork-scene/src/v2/targets.rs@@ -612,6 +612,7 @@ fn node_property(path: &[String], index: usize) -> Result<NodeProperty> {use NodeProperty as P;let name = segment(path, index, "a node property")?;let property = match name {+ "target" => anyhow::bail!("track {}: target is structural; aim at a named node and animate that node's translation instead", display_path(path)),"translation" => P::Translation,"rotation" => P::Rotation,"scale" => P::Scale,@@ -663,6 +664,15 @@ mod tests {segments.iter().map(|s| s.to_string()).collect()}#[test]+ fn target_track_explains_animated_aim() {+ let s = scene();+ let error = s.resolve_target(&path(&["nodes", "cam", "target"]), &s.nodes_by_name()).unwrap_err().to_string();+ assert!(error.contains(r#"["nodes","cam","target"]"#), "{error}");+ assert!(error.contains("aim at a named node"), "{error}");+ assert!(error.contains("animate that node's translation"), "{error}");+ assert!(s.resolve_target(&path(&["nodes", "cam", "translation"]), &s.nodes_by_name()).is_ok());+ }+ #[test]fn camera_optics_are_not_node_track_properties() {let s=scene();for property in ["lens","shift","dof","clip_start","clip_end","ortho_scale"] {diff --git a/crates/vork-scene/src/v2/validate.rs b/crates/vork-scene/src/v2/validate.rsindex ef586e2..7ca9128 100644--- a/crates/vork-scene/src/v2/validate.rs+++ b/crates/vork-scene/src/v2/validate.rs@@ -386,6 +386,17 @@ impl Scene {}}}+ // Camera materials must opt into a ray program before surface-input validation.+ let mut camera_nodes: Vec<_> = self.nodes.iter().collect();+ while let Some(node) = camera_nodes.pop() {+ camera_nodes.extend(&node.children);+ if let NodeKind::Camera { material: Some(name), .. } = &node.kind {+ if let Some(material) = self.materials.get(name) {+ ensure!(material.program != "std/openpbr",+ "camera {:?}: material {name} selects std/openpbr; camera materials require a camera program. Set program:\"std/camera\" beside inputs (e.g. lens), or omit camera.material for default optics. See `vork help cameras`", node.name);+ }+ }+ }// Report every misnamed OpenPBR input at once; authors guess several together.diagnostics::joined(self.materials@@ -565,7 +576,7 @@ impl Scene {"instance count requires a compute binding");}- ensure!(!i.attributes.is_empty(), "instances.attributes must contain at least one column");+ ensure!(!i.attributes.is_empty(), "instances.attributes must contain at least one buffer column (TRANSLATION vec3, ROTATION vec4 xyzw, SCALE vec3, or a custom attribute); columns must have equal lengths");let count = i.attributes.values().filter_map(|name| scene.buffers.get(name).and_then(|b| b.len())).next();for (attribute, b) in &i.attributes {let buffer = scene.buffers.get(b).with_context(|| {@@ -581,7 +592,9 @@ impl Scene {"time_offset" => Some(BufferType::F32),"pass_index" => Some(BufferType::U32), _ => None,};- ensure!(expected.is_none_or(|ty| ty == buffer.element_type), "instances.attributes.{attribute}: wrong buffer type");+ if let Some(expected) = expected {+ ensure!(expected == buffer.element_type, "instances.attributes.{attribute}: buffer {b} has type {:?}; expected {:?}{}", buffer.element_type, expected, if attribute == "ROTATION" { " (xyzw)" } else { "" });+ }if let (Some(count), Some(len)) = (count, buffer.len()) {ensure!(len == count,@@ -1286,6 +1299,16 @@ mod hemisphere_tests {mod orthographic_sensor_tests {use super::*;#[test]+ fn camera_without_program_reports_camera_context() {+ for name in ["eye", ""] {+ let value = serde_json::json!({"version":2,"nodes":[{"type":"camera","name":name,"material":{"inputs":{"lens":35}}}]});+ let scene = crate::v2::from_test_value::<Scene>(value).unwrap();+ let error = format!("{:#}", scene.validate().unwrap_err());+ assert!(error.contains("camera") && error.contains("std/camera"), "{error}");+ assert!(!error.contains("unknown OpenPBR"), "{error}");+ }+ }+ #[test]fn orthographic_cameras_use_fit_and_reject_old_names() -> Result<()> {for fit in ["auto", "vertical", "horizontal"] {let value = serde_json::json!({"version":2,"nodes":[{"type":"camera","material":{"program":"std/camera","inputs":{"projection":"ortho","ortho_scale":4,"fit":fit}}}]});diff --git a/crates/vork-slang/Cargo.toml b/crates/vork-slang/Cargo.tomlindex 98b8b84..7d78cc8 100644--- a/crates/vork-slang/Cargo.toml+++ b/crates/vork-slang/Cargo.toml@@ -6,6 +6,7 @@ license.workspace = true[dependencies]anyhow = "1"+blake3 = "1"serde = { version = "1", features = ["derive"] }serde_json = "1"naga = { version = "29", features = ["wgsl-in", "hlsl-out"] }@@ -13,3 +14,7 @@ vork-scene = { path = "../vork-scene" }[target.'cfg(unix)'.dependencies]libc = "0.2"++[dev-dependencies.vork-scene]+path = "../vork-scene"+features = ["test-support"]diff --git a/crates/vork-slang/build.rs b/crates/vork-slang/build.rsindex 6c24db3..e30cbcc 100644--- a/crates/vork-slang/build.rs+++ b/crates/vork-slang/build.rs@@ -1,9 +1,9 @@fn main() {- // The private corpus and its test modules are intentionally absent from public exports.+ // Explicit opt-in: directory layout must not change test admission.println!("cargo:rustc-check-cfg=cfg(vork_private_tests)");println!("cargo:rerun-if-changed=build.rs");- if std::path::Path::new("../../scenes").is_dir() {- println!("cargo:rerun-if-changed=../../scenes");+ println!("cargo:rerun-if-env-changed=VORK_PRIVATE_TESTS");+ if std::env::var("VORK_PRIVATE_TESTS").as_deref() == Ok("1") {println!("cargo:rustc-cfg=vork_private_tests");}}diff --git a/crates/vork-slang/src/identity.rs b/crates/vork-slang/src/identity.rsnew file mode 100644index 0000000..6806002--- /dev/null+++ b/crates/vork-slang/src/identity.rs@@ -0,0 +1,1080 @@+//! Conservative compiler-input identity. Slang owns lexing, preprocessing and+//! import resolution. Repros retain the bytes actually read, including failed+//! resolution probes; native code generation replays that same filesystem.+use super::*;++pub struct PreparedModules {+ work: Workspace,+ executable: PathBuf,+ module: PathBuf,+ main: PathBuf,+ replay_source: bool,+ args: Vec<String>,+ entries: Vec<(String, String)>,+ snapshot: Snapshot,+ identity: Vec<u8>,+}++/// A cheap exact-input validation receipt, stored by the renderer in its+/// ordinary content-addressed store. Failed resolver probes are dependencies+/// too: a new higher-priority file must force compiler resolution again.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct InputIdentity {+ pub identity: Vec<u8>,+ reads: BTreeMap<PathBuf, Option<Vec<u8>>>,+ reusable: bool,+ resolved: BTreeMap<PathBuf, PathBuf>,+ canonical: BTreeMap<PathBuf, PathBuf>,+}+impl InputIdentity {+ pub fn valid(&self) -> bool {+ self.reusable && self.current()+ }+ fn current(&self) -> bool {+ self+ .reads+ .iter()+ .all(|(path, bytes)| fs::read(path).ok().as_ref() == bytes.as_ref())+ && self+ .canonical+ .iter()+ .all(|(path, target)| path.canonicalize().ok().as_ref() == Some(target))+ }+ /// A portable proof key must cover every resolver input of code generation,+ /// including probes introduced by a generated wrapper. Native composition+ /// separately permits target-only inputs through `verify`.+ pub fn verify_proof(&self, expected: &Self) -> Result<()> {+ self.verify(expected)?;+ ensure!(self.reads.iter().all(|(path,bytes)|expected.reads.get(path)==Some(bytes)),+ "Slang proof read inputs absent from its compiler identity; cannot cache the result");+ Ok(())+ }++ /// Compare shared imported inputs, including unsuccessful search probes+ /// and aliases that resolve to an already loaded module.+ pub fn verify(&self, expected: &Self) -> Result<()> {+ for (path, bytes) in &self.reads {+ if let Some(previous) = expected.reads.get(path) {+ ensure!(+ bytes == previous,+ "Slang import {} changed during compilation; retry the command",+ path.display()+ );+ }+ }+ for (path, target) in &self.resolved {+ if let Some(previous) = expected.resolved.get(path) {+ ensure!(+ target == previous,+ "Slang import resolution {} changed during compilation; retry the command",+ path.display()+ );+ }+ }+ for (path, target) in &self.canonical {+ if let Some(previous) = expected.canonical.get(path) {+ ensure!(+ target == previous,+ "Slang import resolution {} changed during compilation; retry the command",+ path.display()+ );+ }+ }+ Ok(())+ }+}++struct Snapshot {+ repro: PathBuf,+ files: BTreeMap<PathBuf, Vec<u8>>,+ reads: BTreeMap<PathBuf, Option<Vec<u8>>>,+ uncertain: Vec<PathBuf>,+ resolved: BTreeMap<PathBuf, PathBuf>,+ canonical: BTreeMap<PathBuf, PathBuf>,+}++/// Capture each actual proof pass, not a post-compilation read of its depfile.+/// Shared imports must agree between passes, including failed search probes.+pub(super) fn check_imports(compiler: &Compiler, work: &Workspace, repro: PathBuf) -> Result<()> {+ let receipt = Snapshot::read(compiler, repro)?.receipt(work, Vec::new());+ if let Some(expected) = &compiler.expected { receipt.verify(expected)?; }+ if let Some(captured) = &compiler.captured {+ let mut captured = captured.lock().unwrap();+ if let Some(previous) = captured.as_mut() {+ receipt.verify(previous)?;+ previous.reads.extend(receipt.reads);+ previous.resolved.extend(receipt.resolved);+ previous.canonical.extend(receipt.canonical);+ previous.reusable &= receipt.reusable;+ } else {+ *captured = Some(receipt);+ }+ }+ Ok(())+}++fn part(out: &mut Vec<u8>, bytes: &[u8]) {+ out.extend_from_slice(&(bytes.len() as u64).to_le_bytes());+ out.extend_from_slice(bytes);+}++impl Snapshot {+ fn read(compiler: &Compiler, repro: PathBuf) -> Result<Self> {+ let directory = repro.with_extension("");+ if directory.exists() {+ fs::remove_dir_all(&directory)?;+ }+ let output = compiler_output(+ Command::new(&compiler.executable)+ .arg("-extract-repro")+ .arg(&repro),+ )?;+ ensure!(+ output.status.success(),+ "extract Slang dependency snapshot: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let manifest = read_compiler_text(directory.join("manifest.txt"))?;+ Self::read_manifest(repro, &directory, &manifest)+ }++ fn read_manifest(repro: PathBuf, directory: &Path, manifest: &str) -> Result<Self> {+ let mut files = BTreeMap::new();+ let mut extracted = BTreeMap::new();+ let mut reads = BTreeMap::new();+ let mut uncertain = Vec::new();+ let mut uncertain_details = Vec::new();+ let mut resolved = BTreeMap::new();+ let mut section = "";+ for line in manifest.lines() {+ if line.starts_with('[') {+ section = line;+ continue;+ }+ if section == "[files]" {+ let (name, path) = line+ .split_once(" -> ")+ .context("Slang snapshot file mapping")?;+ let bytes = fs::read(directory.join(name))?;+ let path = PathBuf::from(path);+ extracted.insert(name.to_owned(), (path.clone(), bytes.clone()));+ reads.insert(path.clone(), Some(bytes.clone()));+ files.insert(path, bytes);+ } else if section == "[paths]" {+ let (path, name) = line+ .split_once(" -> ")+ .context("Slang snapshot resolution mapping")?;+ let bytes = if matches!(name, "[not loaded]" | "[not found]") {+ None+ } else if let Some((target, bytes)) = extracted.get(name) {+ resolved.insert(PathBuf::from(path), target.clone());+ Some(bytes.clone())+ } else if let Some(bytes) = reads.get(&PathBuf::from(path)) {+ bytes.clone()+ } else {+ uncertain.push(PathBuf::from(path));+ uncertain_details.push(line.to_owned());+ continue;+ };+ reads.insert(PathBuf::from(path), bytes);+ }+ }+ let canonical = reads+ .iter()+ .filter_map(|(path, bytes)| {+ let absolute = if path.is_absolute() {+ path.clone()+ } else {+ repro.parent().unwrap().join(path)+ };+ bytes.as_ref().and_then(|_| {+ absolute+ .canonicalize()+ .ok()+ .map(|target| (absolute, target))+ })+ })+ .collect();+ // An unrecognized external resolver record cannot be omitted from an+ // identity. Fail closed instead of guessing its binding or caching a+ // partial dependency graph.+ let root = repro.parent().context("Slang snapshot directory")?;+ ensure!(+ uncertain.iter().all(|path| {+ let absolute = if path.is_absolute() {+ path.clone()+ } else {+ root.join(path)+ };+ absolute.starts_with(root)+ && !path+ .components()+ .any(|c| c == std::path::Component::ParentDir)+ }),+ "unrecognized external Slang dependency snapshot mapping; cannot establish a safe cache identity: {uncertain_details:?}"+ );+ Ok(Self {+ repro,+ files,+ reads,+ uncertain,+ resolved,+ canonical,+ })+ }+}++impl Snapshot {+ fn receipt(&self, work: &Workspace, identity: Vec<u8>) -> InputIdentity {+ let locate = |path: &Path| {+ if path.is_absolute() {+ path.to_path_buf()+ } else {+ work.0.join(path)+ }+ };+ let reusable = !self+ .uncertain+ .iter()+ .any(|p| !locate(p).starts_with(&work.0))+ && !self.reads.keys().any(|p| {+ locate(p).starts_with(&work.0)+ && p.components().any(|c| c == std::path::Component::ParentDir)+ });+ let reads: BTreeMap<PathBuf, Option<Vec<u8>>> = self+ .reads+ .iter()+ .filter_map(|(path, bytes)| {+ let path = if path.is_absolute() {+ path.clone()+ } else {+ work.0.join(path)+ };+ (!path.starts_with(&work.0)).then(|| (path, bytes.clone()))+ })+ .chain(+ self.files+ .iter()+ .filter(|(p, _)| !p.starts_with(&work.0))+ .map(|(p, b)| (p.clone(), Some(b.clone()))),+ )+ .collect();+ let resolved: BTreeMap<_, _> = self+ .resolved+ .iter()+ .filter(|(p, _)| !locate(p).starts_with(&work.0))+ .map(|(p, t)| (locate(p), locate(t)))+ .collect();+ let canonical: BTreeMap<_, _> = self+ .canonical+ .iter()+ .filter(|(path, _)| !path.starts_with(&work.0))+ .map(|(p, t)| (p.clone(), t.clone()))+ .collect();+ let reusable = reusable+ && resolved.iter().all(|(p, t)| {+ canonical+ .get(p)+ .is_some_and(|c| t.canonicalize().ok().as_ref() == Some(c))+ });+ InputIdentity {+ identity,+ reads,+ reusable,+ resolved,+ canonical,+ }+ }+}++impl Compiler {+ pub fn input_policy(&self) -> String {+ format!("snapshot-v3-checked-module-imports:{VERSION}:{}", self.executable.display())+ }+ pub fn with_identity(&self, identity: &InputIdentity) -> Self {+ Self {+ executable: self.executable.clone(),+ expected: Some(identity.clone()),+ captured: self.captured.clone(),+ }+ }+ /// The current exact receipt associated with a caller's normalized proof key.+ pub fn input_identity(&self) -> Option<&InputIdentity> {+ self.expected.as_ref()+ }++ /// Run a proof against checked compiler input receipts. Changes between+ /// passes or before publication fail rather than caching mismatched output.+ pub fn capture_inputs<T>(&self, build: impl FnOnce(&Compiler) -> Result<T>) -> Result<(T, InputIdentity)> {+ let captured = std::sync::Arc::new(Mutex::new(None));+ let compiler = Self {+ executable: self.executable.clone(), expected: self.expected.clone(),+ captured: Some(captured.clone()),+ };+ let result = build(&compiler)?;+ let receipt = captured.lock().unwrap().take().context("proof did not capture Slang inputs")?;+ ensure!(receipt.current(), "Slang inputs changed during compilation; retry the command");+ Ok((result, receipt))+ }++ /// Resolve and type-check a native entry without downstream optimization.+ /// Supplied modules retain conservative text identity; only reachable ones+ /// participate. External imports use compiler tokens where safe.+ pub fn prepare_modules(+ &self,+ modules: &[(&str, &str)],+ main: &str,+ entries: &[(&str, &str)],+ args: &[&str],+ ) -> Result<PreparedModules> {+ self.prepare_identity(modules, main, entries, args, None, &BTreeMap::new())+ }++ /// Generated material modules have compiler-proven input identities. Use+ /// those rather than allowing original comments in their retained source+ /// to re-enter native keys. Their generator/compiler policy is covered by+ /// the renderer's shader namespace; native-only dependencies are still+ /// resolved and keyed by this request.+ pub fn prepare_identified_modules(+ &self,+ modules: &[(&str, &str)],+ main: &str,+ entries: &[(&str, &str)],+ args: &[&str],+ identities: &BTreeMap<String, Vec<u8>>,+ ) -> Result<PreparedModules> {+ self.prepare_identity(modules, main, entries, args, None, identities)+ }++ fn prepare_identity(+ &self,+ modules: &[(&str, &str)],+ main: &str,+ entries: &[(&str, &str)],+ args: &[&str],+ normalize_root: Option<bool>,+ identities: &BTreeMap<String, Vec<u8>>,+ ) -> Result<PreparedModules> {+ let _progress = crate::progress::Job::start(false);+ self.version()?;+ let work = Workspace::new()?;+ for (name, source) in modules {+ let path = work.0.join(format!("{name}.slang"));+ fs::create_dir_all(path.parent().unwrap())?;+ fs::write(path, source)?;+ }+ let main = work.0.join(format!("{main}.slang"));+ let repro = work.0.join("capture.repro");+ let depfile = work.0.join("capture.d");+ let mut command = Command::new(&self.executable);+ command+ .arg(&main)+ .current_dir(&work.0)+ .arg(INITIALIZATION)+ .arg("-I")+ .arg(&work.0)+ .args(args);+ for (entry, stage) in entries {+ command.args(["-entry", entry, "-stage", stage]);+ }+ let output = compiler_output(+ command+ .args(["-no-codegen", "-notes-disable", "88", "-o"])+ .arg(work.0.join("capture.slang-module"))+ .arg("-depfile")+ .arg(&depfile)+ .arg("-dump-repro")+ .arg(&repro),+ )?;+ ensure!(+ output.status.success(),+ "Slang identity: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let snapshot = Snapshot::read(self, repro)?;+ let mut dependencies: Vec<_> = snapshot.files.keys().cloned().collect();+ dependencies.sort_by_key(|path| path.strip_prefix(&work.0).unwrap_or(path).to_path_buf());+ let mut identity = Vec::new();+ part(&mut identity, if normalize_root.is_some() { b"slang-input-snapshot-v1" } else { b"slang-input-snapshot-v3-checked-module-imports" });+ part(&mut identity, VERSION.as_bytes());+ part(&mut identity, INITIALIZATION.as_bytes());+ let external = snapshot.files.keys().any(|path| !path.starts_with(&work.0));+ let mut options = args.iter();+ while let Some(arg) = options.next() {+ // A wholly embedded closure does not depend on unused external+ // search directories. This keeps bundled programs portable across+ // working directories. Exact-input receipts still validate lookups.+ if !external && *arg == "-I" {+ options.next();+ continue;+ }+ part(&mut identity, arg.as_bytes());+ }+ for (entry, stage) in entries {+ part(&mut identity, entry.as_bytes());+ part(&mut identity, stage.as_bytes());+ }+ for path in dependencies {+ let bytes = snapshot+ .files+ .get(&path)+ .with_context(|| format!("Slang snapshot missing {}", path.display()))?;+ let supplied = path.strip_prefix(&work.0).ok();+ part(+ &mut identity,+ supplied.unwrap_or(&path).to_string_lossy().as_bytes(),+ );+ if let Some(relative) = supplied {+ let name = relative+ .with_extension("")+ .to_string_lossy()+ .replace('\\', "/");+ if let Some(proven) = identities.get(&name) {+ part(&mut identity, b"compiler-proven-material-module");+ part(&mut identity, proven);+ continue;+ }+ }+ let root = path == main;+ // -E is a token stream, not a serialization of preprocessor state.+ // Directives may affect that state without emitting tokens. Keep+ // their raw identity, and do the same for any diagnostic. This is+ // deliberately conservative (even a '#' in a string falls back).+ // Proof diagnostics are part of the cached Program. Native cache+ // payloads contain code only: an unrelated renderer warning must+ // not make a comment in an imported helper invalidate that code.+ let eligible = (normalize_root.is_none() || output.stderr.is_empty())+ && if root && normalize_root.is_some() {+ normalize_root.unwrap()+ } else {+ supplied.is_none() && !bytes.contains(&b'#')+ };+ if supplied.is_none() {+ reject_reserved(std::str::from_utf8(bytes)?, &path.display().to_string())?;+ }+ if eligible {+ let mut command = Command::new(&self.executable);+ command+ .arg("-repro-file-system")+ .arg(&snapshot.repro)+ .arg(&path)+ .current_dir(&work.0)+ .arg(INITIALIZATION)+ .arg("-I")+ .arg(&work.0)+ .args(args)+ .args(["-E", "-line-directive-mode", "none"]);+ let tokens = compiler_output(&mut command)?;+ ensure!(+ tokens.status.success(),+ "preprocess Slang identity: {}",+ String::from_utf8_lossy(&tokens.stderr)+ );+ if tokens.stderr.is_empty() {+ part(&mut identity, &tokens.stdout);+ } else {+ part(&mut identity, bytes);+ }+ } else {+ part(&mut identity, bytes);+ }+ }+ let mut bindings: Vec<_> = snapshot+ .resolved+ .iter()+ .map(|(path, target)| {+ (+ path.strip_prefix(&work.0).unwrap_or(path).to_path_buf(),+ target.strip_prefix(&work.0).unwrap_or(target).to_path_buf(),+ )+ })+ .collect();+ bindings.sort();+ for (path, target) in bindings {+ part(&mut identity, path.to_string_lossy().as_bytes());+ part(&mut identity, target.to_string_lossy().as_bytes());+ }+ // Serialized modules can misbind imports with the same leaf filename+ // (for example std/procedurals and blender/procedurals) when loading a+ // larger shader graph. Replay source against the same captured inputs+ // for these graphs; unique-name graphs retain checked-module reuse.+ let mut names = std::collections::BTreeSet::new();+ let replay_source = snapshot.files.keys()+ .filter(|path| path.extension().is_some_and(|ext| ext == "slang"))+ .any(|path| !names.insert(path.file_name().unwrap().to_owned()));+ let module = work.0.join("capture.slang-module");+ Ok(PreparedModules {+ work,+ executable: self.executable.clone(),+ module,+ main,+ replay_source,+ args: args.iter().map(|s| s.to_string()).collect(),+ entries: entries+ .iter()+ .map(|(e, s)| (e.to_string(), s.to_string()))+ .collect(),+ snapshot,+ identity: blake3::hash(&identity).as_bytes().to_vec(),+ })+ }++ /// Surface proofs share the same normalized root and resolved imports.+ /// The returned compiler checks every proof subprocess's captured imports+ /// against this snapshot before returning a publishable result.+ pub fn prepare_program(+ &self,+ abi: &Abi,+ source: &str,+ origin: &Path,+ ) -> Result<PreparedProgram> {+ self.prepare_bound_program(abi,source,origin,"")+ }++ /// Generated compute bindings are trusted compiler input, separate from+ /// authored source so its reserved-name checks stay identical to compilation.+ pub fn prepare_bound_program(+ &self, abi: &Abi, source: &str, origin: &Path, bindings: &str,+ ) -> Result<PreparedProgram> {+ let work = Workspace::new()?;+ write_modules(&work, abi, source)?;+ let mut modules = Vec::new();+ fn visit(root: &Path, path: &Path, modules: &mut Vec<(String, String)>) -> Result<()> {+ for entry in fs::read_dir(path)? {+ let path = entry?.path();+ if path.is_dir() {+ visit(root, &path, modules)?;+ } else {+ modules.push((+ path.strip_prefix(root)?+ .with_extension("")+ .to_string_lossy()+ .replace('\\', "/"),+ fs::read_to_string(path)?,+ ));+ }+ }+ Ok(())+ }+ visit(&work.0, &work.0, &mut modules)?;+ let program=program_text(source,origin);+ let program=if bindings.is_empty() {program} else {format!("import vork;\n{bindings}\n{program}")};+ modules.push(("program".into(), program));+ let includes = include_paths(origin);+ let mut args = vec!["-target", "wgsl"];+ let include_strings: Vec<_> = includes+ .iter()+ .map(|p| std::env::current_dir().map(|cwd| cwd.join(p).display().to_string()))+ .collect::<std::io::Result<_>>()?;+ for include in &include_strings {+ args.extend(["-I", include]);+ }+ let refs: Vec<_> = modules+ .iter()+ .map(|(n, s)| (n.as_str(), s.as_str()))+ .collect();+ let prepared = self.prepare_identity(+ &refs,+ "program",+ &[],+ &args,+ Some(!source.contains('#') && !bindings.contains('#')),+ &BTreeMap::new(),+ )?;+ let expected = prepared.receipt();+ Ok(PreparedProgram {+ compiler: Compiler {+ executable: self.executable.clone(),+ expected: Some(expected),+ captured: self.captured.clone(),+ },+ prepared,+ })+ }+}++pub struct PreparedProgram {+ compiler: Compiler,+ prepared: PreparedModules,+}+impl PreparedProgram {+ pub fn identity(&self) -> &[u8] {+ self.prepared.identity()+ }+ pub fn compiler(&self) -> &Compiler {+ &self.compiler+ }+ pub fn receipt(&self) -> InputIdentity {+ self.prepared.receipt()+ }+}++impl PreparedModules {+ pub fn identity(&self) -> &[u8] {+ &self.identity+ }+ pub fn receipt(&self) -> InputIdentity {+ self.snapshot.receipt(&self.work, self.identity.clone())+ }+ pub fn compile(&self) -> Result<Vec<u8>> {+ let _progress = crate::progress::Job::start(false);+ let output = self.work.0.join("out");+ let mut command = Command::new(&self.executable);+ // Reuse the checked root where imported leaf names are unambiguous;+ // otherwise replay source. Both paths use the captured filesystem.+ // This module is request-local, never persisted.+ // Options must precede the serialized input: Slang loads its imports+ // while parsing that argument, before seeing any later defines.+ command+ .arg("-repro-file-system")+ .arg(&self.snapshot.repro)+ .current_dir(&self.work.0)+ .arg(INITIALIZATION)+ .arg("-I")+ .arg(&self.work.0)+ .args(&self.args)+ .arg(if self.replay_source { &self.main } else { &self.module });+ for (entry, stage) in &self.entries {+ command.args(["-entry", entry, "-stage", stage]);+ }+ let metal = self.args.windows(2).any(|a| a == ["-target", "metal"]);+ if metal && !self.args.iter().any(|a| a == "-line-directive-mode") {+ command.args(["-line-directive-mode", "none"]);+ }+ let result = compiler_output(command.arg("-o").arg(&output))?;+ ensure!(+ result.status.success(),+ "slangc {}: {}",+ result.status,+ String::from_utf8_lossy(&result.stderr)+ );+ let mut code = fs::read(output)?;+ if metal+ && self.args.windows(2).any(|a| {+ matches!(a[0].as_str(), "-fp-mode" | "-floating-point-mode") && a[1] == "precise"+ })+ {+ let mut prefix =+ b"#pragma METAL fp math_mode(safe)\n#pragma METAL fp contract(off)\n".to_vec();+ prefix.append(&mut code);+ code = prefix;+ }+ Ok(code)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn explicit_missing_import_probes_invalidate_when_a_file_appears() -> Result<()> {+ let work = Workspace::new()?;+ let external = Workspace::new()?;+ let missing = external.0.join("higher_priority.slang");+ let manifest = format!("[files]\n[paths]\n{} -> [not found]\n", missing.display());+ let snapshot = Snapshot::read_manifest(work.0.join("input.slang-repro"), &work.0, &manifest)?;+ let receipt = snapshot.receipt(&work, vec![]);+ assert!(receipt.valid());+ fs::write(&missing, "export static const float value = 2.;")?;+ assert!(!receipt.valid(), "a newly resolved import must invalidate the receipt");+ let manifest = format!("[files]\n[paths]\n{} -> [unknown]\n", missing.display());+ assert!(Snapshot::read_manifest(work.0.join("input.slang-repro"), &work.0, &manifest).is_err());+ Ok(())+ }++ #[test]+ fn proof_capture_rejects_import_changes_between_passes() -> Result<()> {+ let work=Workspace::new()?;+ let helper=work.0.join("helper.slang");+ fs::write(&helper,"public float value(){return 0.25;}")?;+ let origin=work.0.join("main.slang");+ let source="import helper; struct Inputs {}; float3 display(DisplayContext ctx, Inputs inputs){return float3(value());}";+ let compiler=Compiler::discover();+ let result=compiler.capture_inputs(|compiler| {+ compiler.compile_display(&Abi { aov_count: 0, context: Abi::spec_context(), closure: openpbr_fields() },source,&origin,"first")?;+ fs::write(&helper,"public float value(){return 0.75;}")?;+ compiler.compile_display(&Abi { aov_count: 0, context: Abi::spec_context(), closure: openpbr_fields() },source,&origin,"second")+ });+ assert!(format!("{:#}",result.unwrap_err()).contains("changed during compilation"));+ Ok(())+ }++ const SOURCE: &str = "struct Inputs {}; Closure surface(ShadingContext ctx, Inputs inputs) { Closure c; c.base_color=float3(value()); return c; }";++ #[test]+ fn same_leaf_library_imports_replay_captured_source() -> Result<()> {+ let compiler = Compiler::discover();+ let modules = [+ ("main", "import std.procedurals; import blender.procedurals; RWStructuredBuffer<float> result; [numthreads(1,1,1)] void main(uint3 id:SV_DispatchThreadID){float3 p=float3(.1,.2,.3);result[id.x]=magic(p).color.x+brick(p).color.x+wave(p);}"),+ ("std/procedurals", module_source("std/procedurals").unwrap()),+ ("blender/procedurals", module_source("blender/procedurals").unwrap()),+ ];+ for target in ["spirv", "metal"] {+ let args = ["-target", target, "-O2", "-fp-mode", "precise"];+ let entries = [("main", "compute")];+ let prepared = compiler.prepare_modules(&modules, "main", &entries, &args)?;+ assert!(prepared.replay_source, "distinct procedural modules must retain their bindings");+ assert_eq!(prepared.compile()?, compiler.compile_modules(&modules, "main", &entries, &args)?, "{target}: captured replay must preserve imported functions");+ }+ Ok(())+ }++ #[test]+ fn checked_native_module_matches_source_codegen() -> Result<()> {+ let compiler = Compiler::discover();+ let modules = [+ ("main", "import helper; RWStructuredBuffer<float> result; [numthreads(1,1,1)] void main(uint3 id:SV_DispatchThreadID){float x; result[id.x]=value()+x;}"),+ ("helper", "public float value(){return 0.25;}"),+ ];+ for target in ["spirv", "metal"] {+ let args = ["-target", target, "-O2", "-fp-mode", "precise"];+ let entries = [("main", "compute")];+ let prepared = compiler.prepare_modules(&modules, "main", &entries, &args)?;+ assert_eq!(prepared.compile()?, compiler.compile_modules(&modules, "main", &entries, &args)?, "{target}: checked module must preserve codegen, including initialization and precise math");+ }+ Ok(())+ }++ #[test]+ fn program_tokens_reuse_comments_but_invalidate_real_and_imported_changes() -> Result<()> {+ let compiler = Compiler::discover();+ let work = Workspace::new()?;+ let origin = work.0.join("material.slang");+ let helper = work.0.join("helper.slang");+ fs::write(&helper, "public float value(){return 0.25;}\n")?;+ let source = format!("import helper; {SOURCE}");+ let abi = Abi {+ aov_count: 0,+ context: Abi::spec_context(),+ closure: openpbr_fields(),+ };+ let base = compiler.prepare_program(&abi, &source, &origin)?;+ let comment = compiler.prepare_program(+ &abi,+ &format!("// changed description\n{source}\n/* more */"),+ &origin,+ )?;+ assert!(+ base.identity() == comment.identity(),+ "root comment must hit"+ );+ fs::write(+ &helper,+ "// imported description\npublic float value() { return 0.25; }\n",+ )?;+ let comment = compiler.prepare_program(&abi, &source, &origin)?;+ assert!(+ base.identity() == comment.identity(),+ "imported comment must hit"+ );+ fs::write(&helper, "public float value(){return 0.75;}\n")?;+ let edited = compiler.prepare_program(&abi, &source, &origin)?;+ assert!(+ base.identity() != edited.identity(),+ "imported colour edit must miss"+ );+ let edited = compiler.prepare_program(+ &abi,+ &source.replace("float3(value())", "float3(0.5)"),+ &origin,+ )?;+ assert!(+ comment.identity() != edited.identity(),+ "root colour edit must miss"+ );+ fs::remove_file(&helper)?;+ assert!(+ compiler.prepare_program(&abi, &source, &origin).is_err(),+ "deleted import cannot hit"+ );+ fs::write(&helper, "public float value(){return 0.25;}\n")?;+ assert_eq!(+ base.identity(),+ compiler.prepare_program(&abi, &source, &origin)?.identity()+ );+ assert_ne!(+ base.identity(),+ compiler+ .prepare_program(&abi, &format!("#warning check me\n{source}"), &origin)?+ .identity(),+ "diagnostic cannot disappear behind a hit"+ );+ Ok(())+ }++ #[test]+ fn native_snapshot_tracks_resolution_and_codegen_uses_captured_bytes() -> Result<()> {+ let compiler = Compiler::discover();+ let work = Workspace::new()?;+ let first = work.0.join("first");+ let second = work.0.join("second");+ fs::create_dir(&first)?;+ fs::create_dir(&second)?;+ let helper = second.join("helper.slang");+ fs::write(&helper, "public float value(){return 0.25;}")?;+ let main = "import helper; RWStructuredBuffer<float> result; [numthreads(1,1,1)] void main(uint3 id:SV_DispatchThreadID){result[id.x]=value();}";+ let modules = [+ ("main", main),+ ("unused", "public float unrelated(){return 1.;}"),+ ];+ let first_text = first.display().to_string();+ let second_text = second.display().to_string();+ let args = ["-target", "spirv", "-I", &first_text, "-I", &second_text];+ let base = compiler.prepare_modules(&modules, "main", &[("main", "compute")], &args)?;+ let binary = base.compile()?;+ let mut artifacts = BTreeMap::new();+ artifacts.insert(base.identity().to_vec(), binary.clone());+ assert!(base.receipt().valid());+ fs::write(&helper, "// comment\npublic float value(){return 0.25;}")?;+ assert!(+ !base.receipt().valid(),+ "changed imported bytes must revalidate with the compiler"+ );+ let comment = compiler.prepare_modules(+ &[+ ("main", main),+ ("unused", "public float unrelated(){return 9.;}"),+ ],+ "main",+ &[("main", "compute")],+ &args,+ )?;+ assert!(+ base.identity() == comment.identity(),+ "unused modules and imported comments must hit"+ );+ assert_eq!(+ artifacts.get(comment.identity()),+ Some(&binary),+ "comment edit reuses the stored artifact"+ );+ fs::write(&helper, "public float value(){return 0.75;}")?;+ let edited = compiler.prepare_modules(&modules, "main", &[("main", "compute")], &args)?;+ assert_ne!(base.identity(), edited.identity());+ assert!(+ !artifacts.contains_key(edited.identity()),+ "real imported edit must miss"+ );+ assert_ne!(+ binary,+ edited.compile()?,+ "semantic import edit must produce a new artifact"+ );+ assert_eq!(+ binary,+ base.compile()?,+ "concurrent edit cannot change the keyed snapshot's code"+ );+ fs::write(+ first.join("helper.slang"),+ "public float value(){return 0.5;}",+ )?;+ assert!(+ !edited.receipt().valid(),+ "a previously failed resolution probe is now a file"+ );+ let shadowed = compiler.prepare_modules(&modules, "main", &[("main", "compute")], &args)?;+ assert_ne!(+ edited.identity(),+ shadowed.identity(),+ "new higher-priority file must invalidate"+ );+ assert_ne!(edited.compile()?, shadowed.compile()?);+ Ok(())+ }++ #[test]+ fn proven_generated_modules_do_not_reintroduce_original_comments() -> Result<()> {+ let compiler = Compiler::discover();+ let work = Workspace::new()?;+ let abi = Abi {+ aov_count: 0,+ context: Abi::spec_context(),+ closure: openpbr_fields(),+ };+ let origin = work.0.join("material.slang");+ let material = "public float value(){return 0.25;}";+ let main = "import material; RWStructuredBuffer<float> result; [numthreads(1,1,1)] void main(uint3 id:SV_DispatchThreadID){result[id.x]=value();}";+ let proof = compiler.prepare_program(&abi, material, &origin)?;+ let ids = BTreeMap::from([("material".into(), proof.identity().to_vec())]);+ let args = ["-target", "spirv"];+ let base = compiler.prepare_identified_modules(+ &[("main", main), ("material", material)],+ "main",+ &[("main", "compute")],+ &args,+ &ids,+ )?;+ let binary = base.compile()?;+ let comment = format!("// retained source after a proof-cache rebuild\n{material}");+ let comment_proof = compiler.prepare_program(&abi, &comment, &origin)?;+ assert_eq!(proof.identity(), comment_proof.identity());+ let comment = compiler.prepare_identified_modules(+ &[("main", main), ("material", &comment)],+ "main",+ &[("main", "compute")],+ &args,+ &ids,+ )?;+ assert_eq!(base.identity(), comment.identity());+ let edit = material.replace("0.25", "0.75");+ let edited_proof = compiler.prepare_program(&abi, &edit, &origin)?;+ let ids = BTreeMap::from([("material".into(), edited_proof.identity().to_vec())]);+ let edited = compiler.prepare_identified_modules(+ &[("main", main), ("material", &edit)],+ "main",+ &[("main", "compute")],+ &args,+ &ids,+ )?;+ assert_ne!(base.identity(), edited.identity());+ assert_ne!(binary, edited.compile()?);+ Ok(())+ }++ #[test]+ fn unrelated_native_diagnostics_do_not_invalidate_imported_comments() -> Result<()> {+ let compiler = Compiler::discover();+ let work = Workspace::new()?;+ let helper = work.0.join("helper.slang");+ fs::write(&helper, "public float value(){return 0.25;}")?;+ let include = work.0.display().to_string();+ let args = ["-target", "spirv", "-I", &include];+ let main = "#warning renderer diagnostic\nimport helper; RWStructuredBuffer<float> result; [numthreads(1,1,1)] void main(uint3 id:SV_DispatchThreadID){result[id.x]=value();}";+ let base =+ compiler.prepare_modules(&[("main", main)], "main", &[("main", "compute")], &args)?;+ fs::write(+ &helper,+ "// imported description\npublic float value(){return 0.25;}",+ )?;+ let comment =+ compiler.prepare_modules(&[("main", main)], "main", &[("main", "compute")], &args)?;+ assert_eq!(base.identity(), comment.identity());+ Ok(())+ }++ #[test]+ fn target_only_imports_invalidate_native_artifacts_on_both_targets() -> Result<()> {+ let compiler = Compiler::discover();+ let work = Workspace::new()?;+ fs::write(+ work.0.join("helper.slang"),+ "#if defined(NATIVE_LINK)\nimport leaf;\npublic float value(){return leaf_value();}\n#else\npublic float value(){return 0.25;}\n#endif\n",+ )?;+ let leaf = work.0.join("leaf.slang");+ let origin = work.0.join("material.slang");+ let source = format!("import helper; {SOURCE}");+ let abi = Abi {+ aov_count: 0,+ context: Abi::spec_context(),+ closure: openpbr_fields(),+ };+ let proof = compiler.prepare_program(&abi, &source, &origin)?;+ let main = "import helper; RWStructuredBuffer<float> result; [numthreads(1,1,1)] void main(uint3 id:SV_DispatchThreadID){result[id.x]=value();}";+ let include = work.0.display().to_string();+ for target in ["spirv", "metal"] {+ fs::write(&leaf, "public float leaf_value(){return 0.25;}")?;+ let args = ["-target", target, "-DNATIVE_LINK=1", "-I", &include];+ let before = compiler.prepare_modules(+ &[("main", main)],+ "main",+ &[("main", "compute")],+ &args,+ )?;+ let binary = before.compile()?;+ fs::write(&leaf, "public float leaf_value(){return 0.75;}")?;+ assert!(!before.receipt().valid());+ let after = compiler.prepare_modules(+ &[("main", main)],+ "main",+ &[("main", "compute")],+ &args,+ )?;+ assert_ne!(before.identity(), after.identity());+ assert_ne!(+ binary,+ after.compile()?,+ "{target}: native-only import must change code"+ );+ assert_eq!(+ proof.identity(),+ compiler.prepare_program(&abi, &source, &origin)?.identity(),+ "the WGSL proof alone does not see this dependency"+ );+ }+ Ok(())+ }++ #[test]+ #[cfg(unix)]+ fn changing_a_symlink_revalidates_even_when_its_bytes_match() -> Result<()> {+ let compiler = Compiler::discover();+ let work = Workspace::new()?;+ let first = work.0.join("one");+ let second = work.0.join("two");+ fs::create_dir(&first)?;+ fs::create_dir(&second)?;+ for directory in [&first, &second] {+ fs::write(+ directory.join("helper.slang"),+ "public float value(){return 0.25;}",+ )?;+ }+ let link = work.0.join("selected");+ std::os::unix::fs::symlink(&first, &link)?;+ let include = link.display().to_string();+ let args = ["-target", "spirv", "-I", &include];+ let main = "import helper; RWStructuredBuffer<float> result; [numthreads(1,1,1)] void main(uint3 id:SV_DispatchThreadID){result[id.x]=value();}";+ let base =+ compiler.prepare_modules(&[("main", main)], "main", &[("main", "compute")], &args)?;+ assert!(base.receipt().valid());+ let binary = base.compile()?;+ fs::remove_file(&link)?;+ std::os::unix::fs::symlink(&second, &link)?;+ assert!(+ !base.receipt().valid(),+ "matching file bytes do not prove the same resolution"+ );+ fs::write(+ second.join("helper.slang"),+ "public float value(){return 0.75;}",+ )?;+ let edited =+ compiler.prepare_modules(&[("main", main)], "main", &[("main", "compute")], &args)?;+ assert_ne!(base.identity(), edited.identity());+ assert_ne!(binary, edited.compile()?);+ Ok(())+ }++ #[test]+ fn proof_cannot_publish_against_an_old_dependency_snapshot() -> Result<()> {+ let compiler = Compiler::discover();+ let work = Workspace::new()?;+ fs::write(+ work.0.join("helper.slang"),+ "public float value(){return 0.25;}",+ )?;+ let source = format!("import helper; {SOURCE}");+ let origin = work.0.join("material.slang");+ let abi = Abi {+ aov_count: 0,+ context: Abi::spec_context(),+ closure: openpbr_fields(),+ };+ let prepared = compiler.prepare_program(&abi, &source, &origin)?;+ fs::write(+ work.0.join("helper.slang"),+ "public float value(){return 0.75;}",+ )?;+ let error = prepared+ .compiler()+ .stages(&abi, &source, &origin)+ .unwrap_err();+ assert!(+ format!("{error:#}").contains("changed during compilation"),+ "{error:#}"+ );+ Ok(())+ }+}diff --git a/crates/vork-slang/src/lib.rs b/crates/vork-slang/src/lib.rsindex 131f7ab..ebe0fcd 100644--- a/crates/vork-slang/src/lib.rs+++ b/crates/vork-slang/src/lib.rs@@ -9,6 +9,8 @@//! programs can be concatenated into one scene shader. The kernel side of the//! boundary is described by [`Abi`]; see docs/PROGRAMS.md.mod image_native;+mod identity;+pub use identity::{InputIdentity, PreparedModules, PreparedProgram};use anyhow::{Context, Result, bail, ensure};use serde::{Deserialize, Serialize};use serde_json::Value;@@ -83,6 +85,7 @@ mod declarations;mod hair;pub use hair::{HAIR_VEC4S, hair_fields};mod openpbr;+pub mod progress;pub mod registry;pub mod renderer_registry;pub use openpbr::openpbr_fields;@@ -169,6 +172,8 @@ pub const NO_IMAGE: u32 = u32::MAX;pub struct Compiler {executable: PathBuf,+ expected: Option<InputIdentity>,+ captured: Option<std::sync::Arc<Mutex<Option<InputIdentity>>>>,}#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]@@ -794,12 +799,27 @@ pub struct Program {/// Every Slang file read besides the program source (imports); callers/// caching a Program must revalidate these.pub dependencies: Vec<PathBuf>,+ /// Install-local bytes from the identity snapshot, refreshed even on a+ /// proof-cache hit. Native linking must not race ahead of those proofs.+ #[serde(skip)]+ pub install_identity: Option<InputIdentity>,pub warnings: String,+ /// Authored stages that this closure cannot execute, independent of compiler diagnostics.+ pub dropped_stages: Vec<String>,/// The closure-effect probe (`Compiler::surface_effects`) as WGSL.pub effects: String,}impl Program {+ /// Refresh diagnostic locations when reusing a compiler-token-identical proof.+ /// The owned wrapper follows the last marker, even if source comments quote it.+ pub fn set_native_source(&mut self, source: &str, origin: &Path) -> Result<()> {+ let generated = self.slang.rsplit_once("\n#line 1 \"<vork program wrapper>\"\n")+ .context("program is missing its generated native wrapper")?.1;+ self.slang = program_text(source, origin) + generated;+ self.include = include_paths(origin);+ Ok(())+ }pub fn needs_spectral(&self, _abi: &Abi, words: &[Option<u32>]) -> Result<bool> {Ok(self.effect_probe()?.needs_spectral(words))}@@ -819,6 +839,7 @@ impl std::fmt::Display for CompilerUnavailable {}impl std::error::Error for CompilerUnavailable {}+impl Compiler {/// Explicit override, installed companion toolchain, then developer PATH.pub fn discover() -> Self {@@ -839,8 +860,22 @@ impl Compiler {Self::new(executable)}pub fn new(executable: impl Into<PathBuf>) -> Self {+ let executable=executable.into();+ // The executable directory is an implicit Slang module search path.+ // An exact-input receipt must not survive selection of another compiler+ // through PATH, even when both report the pinned version.+ let name=if cfg!(windows) && executable.extension().is_none() {executable.with_extension("exe")} else {executable.clone()};+ let resolved=if executable.components().count()==1 && !executable.is_absolute() {+ std::env::var_os("PATH").and_then(|paths| std::env::split_paths(&paths)+ .map(|directory|directory.join(&name))+ .find(|path|path.is_file()))+ } else {Some(executable.clone())};+ let resolved=resolved.map(|path|std::env::current_dir().map_or(path.clone(),|cwd|cwd.join(path)));+ let executable=resolved.and_then(|path|if cfg!(windows) {Some(path)} else {path.canonicalize().ok()}).unwrap_or(executable);Self {- executable: executable.into(),+ executable,+ expected: None,+ captured: None,}}pub fn version(&self) -> Result<String> {@@ -886,6 +921,7 @@ impl Compiler {fs::write(path, source)?;}let output = work.0.join("out");+ let _progress = progress::Job::start(false);let mut command = Command::new(&self.executable);command.arg(work.0.join(format!("{main}.slang")))@@ -905,6 +941,8 @@ impl Compiler {command.args(["-line-directive-mode", "none"]);}let depfile = work.0.join("out.d");+ let repro = work.0.join("native.repro");+ if self.expected.is_some() || self.captured.is_some() { command.arg("-dump-repro").arg(&repro); }let result = compiler_output(command.arg("-depfile").arg(&depfile).arg("-o").arg(&output)).context("run Slang compiler")?;ensure!(@@ -915,6 +953,9 @@ impl Compiler {);// Native-only branches (e.g. VORK_NATIVE_MEDIUM) may import authored modules the WGSL probe never saw.reject_reserved_dependencies(&work, &depfile_paths(&read_compiler_text(depfile)?))?;+ if self.expected.is_some() || self.captured.is_some() {+ identity::check_imports(self, &work, repro)?;+ }let mut code=fs::read(output)?;// Slang emits MSL source; its fp-mode flag cannot configure the later// Metal compiler invocation in a passthrough API. Carry the precise@@ -938,7 +979,7 @@ impl Compiler {origin: &Path,tag: &str,) -> Result<Program> {- let mut ignored_stages = String::new();+ let mut ignored_stages = Vec::new();let mut is_hair = false;let mut capabilities = ProgramCapabilities::default();let capacity = std::cell::Cell::new(openpbr::BLEND_LOBES);@@ -965,9 +1006,9 @@ impl Compiler {if capabilities.lobes && capabilities.blend_lobes.is_none() {wrapper = checked_blend_wrapper(wrapper, capacity.get());}- if is_hair && capabilities.lit { ignored_stages.push_str("warning: ignored lit stage on Hair\n"); capabilities.lit=false; }+ if is_hair && capabilities.lit { ignored_stages.push("lit".into()); capabilities.lit=false; }if declarations.contains("aov") { wrapper.push_str(&abi.aov_function("export", inputs, tag)); }- if is_hair && capabilities.displacement { ignored_stages.push_str("warning: ignored displacement on Hair\n"); capabilities.displacement=false; }+ if is_hair && capabilities.displacement { ignored_stages.push("displace".into()); capabilities.displacement=false; }if capabilities.displacement { wrapper.push_str(&abi.displacement_function("export", inputs, tag)); }if capabilities.lit { wrapper.push_str(&abi.lit_function("export", inputs, tag)); }Ok(wrapper)@@ -1026,7 +1067,9 @@ impl Compiler {include: include_paths(origin),inputs,dependencies: pass.dependencies,- warnings: format!("{}{}", pass.diagnostics, ignored_stages),+ install_identity: None,+ warnings: pass.diagnostics,+ dropped_stages: ignored_stages,effects,})}@@ -1220,8 +1263,11 @@ impl Compiler {work.0.join("program.d"),);fs::write(&input, source)?;+ let _progress = progress::Job::start(false);let mut command = Command::new(&self.executable);command.arg(&input).arg(INITIALIZATION).current_dir(&work.0);+ let repro = work.0.join(if probe { "probe.repro" } else { "proof.repro" });+ if self.expected.is_some() || self.captured.is_some() { command.arg("-dump-repro").arg(&repro); }// Image programs execute directly as WGSL; give their numeric loops// the same speed optimization level as the native renderer shaders.if optimize {command.arg("-O2");}@@ -1258,6 +1304,9 @@ impl Compiler {);let dependencies = depfile_paths(&read_compiler_text(depfile)?);reject_reserved_dependencies(work, &dependencies)?;+ if self.expected.is_some() || self.captured.is_some() {+ identity::check_imports(self, work, repro)?;+ }Ok(Output {wgsl: read_compiler_text(wgsl)?,reflection: serde_json::from_slice(&fs::read(reflection)?)?,@@ -1536,6 +1585,54 @@ mod ast_tests {Ok(())}+ #[test]+ #[ignore = "requires pinned Slang toolchain"]+ fn reused_native_source_refreshes_locations_without_changing_proofs() -> Result<()> {+ let abi = Abi { aov_count: 0, context: Abi::spec_context(), closure: openpbr_fields() };+ let compiler = Compiler::discover();+ let source = "/*\n#line 1 \"<vork program wrapper>\"\n*/\nstruct Inputs {}; Closure surface(ShadingContext c, Inputs i) {return unlit(float3(1.));}";+ let mut program = compiler.compile_surface(&abi, source, Path::new("first.slang"), "relocate")?;+ let original_native = program.slang.clone();+ program.set_native_source(source, Path::new("first.slang"))?;+ assert_eq!(program.slang, original_native, "an unchanged source must keep identical native code");+ let wgsl = program.wgsl.clone();+ let moved = format!("// moved\n// twice\n{source}");+ program.set_native_source(&moved, Path::new("author/second.slang"))?;+ assert_eq!(program.wgsl, wgsl, "source locations must not change the reused proof");+ assert_eq!(program.include, vec![PathBuf::from("author")]);+ assert!(program.slang.starts_with(&format!("import vork;\n#line 1 \"author/second.slang\"\n{moved}\n")));+ assert!(!program.slang.contains("first.slang"));+ // Compile the refreshed native text too: quoting the owned marker in+ // an authored comment must not duplicate or truncate its declarations.+ let native = format!("{}\n[shader(\"compute\")][numthreads(1,1,1)] void vork_entry() {{}}", program.slang);+ let work = Workspace::new()?;+ write_modules(&work, &abi, "")?;+ compiler.run(&work, &native, &[work.0.clone()], true)?;+ Ok(())+ }++ #[test]+ fn private_constant_tables_are_safe_but_writes_are_refused() -> Result<()> {+ let abi = Abi { aov_count: 0, context: Abi::spec_context(), closure: openpbr_fields() };+ let table = "var<private> table: array<f32,2> = array<f32,2>(1.,2.);";+ validate(&format!("{table} fn lookup(i:u32)->f32 {{return table[i];}}"), &abi)?;+ for body in ["table[0]=3.;", "write();"] {+ let wgsl = format!("{table} fn write() {{table[1]=4.;}} fn use_table() {{{body}}}");+ assert!(validate(&wgsl, &abi).unwrap_err().to_string().contains("read-only"));+ }+ Ok(())+ }++ #[test]+ #[ignore = "requires pinned Slang toolchain"]+ fn static_const_array_compiles_with_dynamic_index() -> Result<()> {+ let abi = Abi { aov_count: 0, context: Abi::spec_context(), closure: openpbr_fields() };+ Compiler::discover().compile_surface(&abi,+ "struct Inputs {}; static const float3 colors[2]={float3(1,0,0),float3(0,1,0)}; Closure surface(ShadingContext c, Inputs i) {return unlit(colors[uint(c.time)%2]);}",+ Path::new("author/palette.slang"), "palette")?;+ Ok(())+ }+#[test]fn optional_stage_probe_rejects_unrecognized_function_records() {let record = "\nFuncDecl:\n{\n parentDecl : ModuleDecl: module\n nameAndLoc : NameLoc{\"medium\"}\n}";@@ -1598,7 +1695,6 @@ fn depfile_paths(text: &str) -> Vec<PathBuf> {fn isolate(wgsl: &str, tag: &str, allow_workgroup: bool) -> Result<String> {ensure!(!wgsl.contains("@binding")- && !wgsl.contains("var<private>")&& (allow_workgroup || !wgsl.contains("var<workgroup>")),"programs may not declare global resources or variables");@@ -1661,7 +1757,7 @@ fn validated_module(wgsl: &str, abi: &Abi) -> Result<naga::Module> {.unwrap();let parsed = naga::front::wgsl::parse_str(&module).map_err(|e| anyhow::anyhow!(e.emit_to_string(&module)))?;- naga::valid::Validator::new(+ let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(),// Half packing is ordinary f32 arithmetic, also used by compositor// working images; it does not enable native f16 shader types.@@ -1669,6 +1765,15 @@ fn validated_module(wgsl: &str, abi: &Abi) -> Result<naga::Module> {).validate(&parsed).map_err(|e| anyhow::anyhow!("{e:?}"))?;+ for (global, variable) in parsed.global_variables.iter() {+ if variable.space != naga::AddressSpace::Private { continue; }+ let writes = naga::valid::GlobalUse::WRITE | naga::valid::GlobalUse::ATOMIC;+ ensure!(variable.init.is_some()+ && parsed.functions.iter().all(|(f, _)| !info[f][global].intersects(writes))+ && (0..parsed.entry_points.len()).all(|e| !info.get_entry_point(e)[global].intersects(writes)),+ "program global {:?} must be initialized and read-only; use Inputs or compute buffers for mutable state; see vork help programs",+ variable.name);+ }Ok(parsed)}diff --git a/crates/vork-slang/src/progress.rs b/crates/vork-slang/src/progress.rsnew file mode 100644index 0000000..ab2f1d1--- /dev/null+++ b/crates/vork-slang/src/progress.rs@@ -0,0 +1,52 @@+//! Optional process progress, enabled by the CLI. No output or observer thread in library users.+use std::sync::{Mutex, OnceLock, atomic::{AtomicUsize, Ordering}};++#[derive(Clone, Default)]+pub struct State {+ pub phase: &'static str,+ pub total: usize,+ pub shaders_started: usize,+ pub shaders_done: usize,+ pub pipelines_started: usize,+ pub pipelines_done: usize,+}+static STATE: OnceLock<Mutex<State>> = OnceLock::new();+static COMPLETED: AtomicUsize = AtomicUsize::new(0);++pub fn enable(phase: &'static str) {+ *STATE.get_or_init(Default::default).lock().unwrap() = State { phase, ..Default::default() };+ COMPLETED.store(0, Ordering::Relaxed);+}+pub fn phase(phase: &'static str, total: usize) {+ if let Some(state) = STATE.get() {+ let mut state = state.lock().unwrap();+ state.phase = phase;+ state.total = total;+ COMPLETED.store(0, Ordering::Relaxed);+ }+}+/// One atomic update per delivered frame/setup configuration; never called in a sample or GPU loop.+pub fn completed(count: usize) { COMPLETED.fetch_max(count, Ordering::Relaxed); }+pub fn snapshot() -> (State, usize) {+ (STATE.get().expect("progress enabled").lock().unwrap().clone(), COMPLETED.load(Ordering::Relaxed))+}+/// Count Slang invocations and driver pipeline creations, including driver-only work.+pub struct Job { driver: bool, enabled: bool }+impl Job {+ pub fn start(driver: bool) -> Self {+ let enabled = STATE.get().is_some();+ if let Some(state) = STATE.get() {+ let mut state = state.lock().unwrap();+ if driver { state.pipelines_started += 1; } else { state.shaders_started += 1; }+ }+ Self { driver, enabled }+ }+}+impl Drop for Job {+ fn drop(&mut self) {+ if self.enabled {+ let mut state = STATE.get().unwrap().lock().unwrap();+ if self.driver { state.pipelines_done += 1; } else { state.shaders_done += 1; }+ }+ }+}diff --git a/crates/vork-slang/src/registry.rs b/crates/vork-slang/src/registry.rsindex 2d413bb..fbbfc81 100644--- a/crates/vork-slang/src/registry.rs+++ b/crates/vork-slang/src/registry.rs@@ -244,8 +244,8 @@ registry! {REFLECTION_DISPATCH_PIXELS: u32 => u32, "REG_REFLECTION_DISPATCH_PIXELS" = 16384;/// One u32 visibility mask word per pixel invocation.REFLECTION_BATCH_SAMPLES: u32 => u32, "REG_REFLECTION_BATCH_SAMPLES" = 32;- /// Secondary medium rays retain all samples across bounded invocations.- MEDIUM_GI_RAY_BATCH: u32 => u32, "REG_MEDIUM_GI_RAY_BATCH" = 1;+ /// Diffuse GI retains all samples across bounded invocations, with or without media.+ GI_RAY_BATCH: u32 => u32, "REG_GI_RAY_BATCH" = 1;MEDIUM_REFLECTION_RAY_BATCH: u32 => u32, "REG_MEDIUM_REFLECTION_RAY_BATCH" = 1;/// Retain boundary cursors only across a short primary-lighting depth batch.MEDIUM_LIGHTING_DEPTH_BATCH: u32 => u32, "REG_MEDIUM_LIGHTING_DEPTH_BATCH" = 4;diff --git a/crates/vork-slang/tests/compiler.rs b/crates/vork-slang/tests/compiler.rsindex e719674..ce78039 100644--- a/crates/vork-slang/tests/compiler.rs+++ b/crates/vork-slang/tests/compiler.rs@@ -613,3 +613,16 @@ fn std_display_programs_own_grading_and_pixel_context() {}}}++#[test]+#[ignore = "requires pinned Slang toolchain"]+fn hair_dropped_stages_survive_compiler_cache_serialization() {+ let source = format!("{}\nClosure lit(ShadingContext ctx, Inputs inputs, Lighting lighting) {{Closure c={{}};return c;}}\nfloat3 displace(DisplacementContext ctx, Inputs inputs) {{return float3(1);}}",+ vork_slang::module_source("std/hair").unwrap());+ let program = Compiler::discover().compile_surface(&abi(), &source, Path::new("hair-stages.slang"), "hairstages").unwrap();+ assert!(program.capabilities.hair);+ assert!(!program.capabilities.lit && !program.capabilities.displacement);+ assert_eq!(program.dropped_stages, ["lit", "displace"]);+ let cached: vork_slang::Program = serde_json::from_slice(&serde_json::to_vec(&program).unwrap()).unwrap();+ assert_eq!(cached.dropped_stages, program.dropped_stages);+}diff --git a/crates/vork-std/Cargo.toml b/crates/vork-std/Cargo.tomlindex 590f7d1..38ec598 100644--- a/crates/vork-std/Cargo.toml+++ b/crates/vork-std/Cargo.toml@@ -14,7 +14,8 @@ rquickjs = "0.12.2"serde_json = "1"serde = { version = "1", features = ["derive"] }-ttf-parser = "0.25.1"+# Maintained 0.25.1 fork; preserves the outline, metric and legacy kern APIs.+ttf-parser = { package = "xberg-ttf-parser", version = "1.1" }lyon_path = "1"lyon_tessellation = "1"diff --git a/crates/vork-std/README.md b/crates/vork-std/README.mdindex 9b75d52..79e69cd 100644--- a/crates/vork-std/README.md+++ b/crates/vork-std/README.md@@ -22,7 +22,8 @@ Scene geometry builders remain available.`text` is a native std loader: it reads the supplied TrueType/OpenType font with-MIT/Apache-2.0 ttf-parser and tessellates outlines with MIT/Apache-2.0 Lyon. It emits+MIT xberg-ttf-parser (the maintained ttf-parser fork) and tessellates outlines with+MIT/Apache-2.0 Lyon. It emitsordinary buffer/geometry fragments, with counters, kerning, multiline alignment,extrusion and rounded bevels. The QuickJS runtime keeps no host bindings.`text(name, options)` in the Node SDK calls the installed `vork std text` loader;diff --git a/crates/vork-std/src/help.txt b/crates/vork-std/src/help.txtindex f8dd0c8..1c83a86 100644--- a/crates/vork-std/src/help.txt+++ b/crates/vork-std/src/help.txt@@ -1,2 +1 @@expand: scene JSON → scene JSON with buffer geometry; font paths relative to working directory-InstanceFragment: {buffers:{ [k: string]: Buffer; },instances:Instances}diff --git a/crates/vork-std/src/lib.rs b/crates/vork-std/src/lib.rsindex 261b20f..96ed4b9 100644--- a/crates/vork-std/src/lib.rs+++ b/crates/vork-std/src/lib.rs@@ -1,6 +1,6 @@//! Unstable, internal: all Rust APIs in this crate are free to change.//!-//! Language-independent JSON fragments from the same implementation as @usevoyager/vork.+//! Language-independent JSON fragments from the same implementation as @voyager-so/vork.//! The embedded engine has no host bindings, filesystem or network access.mod expand;pub use expand::{expand_scene, load_scene};@@ -66,6 +66,12 @@ pub fn evaluate(function: &str, argument: &str) -> Result<String> {mod tests {use super::*;+ #[test]+ fn scatter_is_not_a_standard_library_function() {+ let error = evaluate("scatter", "{}").unwrap_err().to_string();+ assert!(error.contains("unknown standard-library function scatter"), "{error}");+ }+#[test]fn geometry_names_default_to_builder() {for (builder, options) in [diff --git a/crates/vork-std/src/sdk.js b/crates/vork-std/src/sdk.jsindex 72acce3..e836ee7 100644--- a/crates/vork-std/src/sdk.js+++ b/crates/vork-std/src/sdk.js@@ -60,15 +60,6 @@ const ROUNDED_BOX_SEGMENTS = 8;* turning by more than this is sharp (split normals); gentler corners share a smooth normal.* vork-std's native extrude repeats it (crates/vork-std/src/extrude.rs). */const SMOOTH_ANGLE_DEGREES = 30;-/** Numerical Recipes uint32 LCG: reproducible seeded sampling across host languages. */-const LCG_MULTIPLIER = 1664525;-const LCG_INCREMENT = 1013904223;-/** Exact uint32 range used to normalize seeded random values to [0,1). */-const UINT32_RANGE = 4294967296;-/** MurmurHash3 fmix32 avalanche constants decorrelate adjacent author seeds. */-const SEED_MIX_MULTIPLIER_A = 0x85ebca6b;-const SEED_MIX_MULTIPLIER_B = 0xc2b2ae35;-const SEED_MIX_SHIFTS = [16, 13, 16];/** SDK authoring choice: externalize buffers of at least 4 KiB to keep scene JSON readable. */const BINARY_BUFFER_MIN_BYTES = 4096;@@ -84,18 +75,6 @@ function cross(a, b) {}-/** Internal deterministic generator; fmix32 decorrelates adjacent author seeds before the LCG. */-function seededRandom(seed) {- if (!Number.isInteger(seed) || seed < 0 || seed >= UINT32_RANGE)- throw new RangeError('seed must be a uint32');- let state = seed;- state = Math.imul(state ^ (state >>> SEED_MIX_SHIFTS[0]), SEED_MIX_MULTIPLIER_A);- state = Math.imul(state ^ (state >>> SEED_MIX_SHIFTS[1]), SEED_MIX_MULTIPLIER_B);- state = (state ^ (state >>> SEED_MIX_SHIFTS[2])) >>> 0;- return () => { state = (Math.imul(state, LCG_MULTIPLIER) + LCG_INCREMENT) >>> 0; return state / UINT32_RANGE; };-}--/** Valid options for each shape constructor. */@@ -492,132 +471,6 @@ function revolve(name = "revolve", { profile, segments: count = SHAPE_LONGITUDESreturn mesh.finish(name);}----function positiveInteger(value, field) {- if (!Number.isSafeInteger(value) || value < 1)- throw new RangeError(`${field} must be a positive safe integer`);- return value;-}-function finish(name, transforms) {- checkName(name, 'instance name');- const translation = `${name}_translation`, rotation = `${name}_rotation`;- const quaternions = transforms.map(m => {- const diagonal = [m[0], m[5], m[10]];- const trace = diagonal[0] + diagonal[1] + diagonal[2];- const q = [0, 0, 0, 0];- if (trace > 0) {- const s = 2 * Math.sqrt(1 + trace);- q[0] = (m[6] - m[9]) / s;- q[1] = (m[8] - m[2]) / s;- q[2] = (m[1] - m[4]) / s;- q[3] = s / 4;- }- else {- const i = diagonal.indexOf(Math.max(...diagonal)), j = (i + 1) % 3, k = (i + 2) % 3;- const s = 2 * Math.sqrt(1 + diagonal[i] - diagonal[j] - diagonal[k]);- q[i] = s / 4;- q[j] = (m[j * 4 + i] + m[i * 4 + j]) / s;- q[k] = (m[k * 4 + i] + m[i * 4 + k]) / s;- q[3] = (m[j * 4 + k] - m[k * 4 + j]) / s;- }- const length = Math.hypot(...q);- return q.map(v => v / length);- });- return { buffers: {- [translation]: { type: 'vec3', data: transforms.map(m => m.slice(12, 15)) },- [rotation]: { type: 'vec4', data: quaternions },- }, instances: { attributes: { TRANSLATION: translation, ROTATION: rotation } } };-}-/** Uniform area sampling over one inline triangle geometry; local +Y follows the face normal.- * Transforms use the source geometry's local space; give the instanced node the surface- * node's transform, or parent it under that node. The seed is a uint32. */-function scatter(onGeometry, count, seed, name) {- positiveInteger(count, 'count');- const random = seededRandom(seed);- const geometries = Object.values(onGeometry.geometry);- if (geometries.length !== 1)- throw new RangeError('scatter requires exactly one geometry');- const geometry = geometries[0];- name ??= `${Object.keys(onGeometry.geometry)[0]}_scatter`;- checkName(name, 'instance name');- if (geometry.topology !== undefined && geometry.topology !== 'triangles')- throw new RangeError('scatter requires triangle topology');- const position = geometry.attributes.POSITION;- const source = typeof position === 'string' ? onGeometry.buffers[position] : position;- if (!source || source.type !== 'vec3' || !source.data || source.file)- throw new RangeError('scatter requires inline vec3 positions');- const numbers = (value) => {- if (typeof value === 'number' && Number.isFinite(value))- return [value];- if (Array.isArray(value))- return value.flatMap(numbers);- throw new RangeError('scatter buffers require finite numeric data');- };- if ((source.offset ?? 0) !== 0 || source.count != null)- throw new RangeError('inline scatter buffers cannot have offset/count');- const positionRows = Array.from(source.data, numbers);- if (!positionRows.every(row => row.length === 3))- throw new RangeError('scatter positions require vec3 elements');- const positions = positionRows.flat();- if (positions.length % 3 !== 0)- throw new RangeError('scatter positions require complete vec3 elements');- let indices;- if (geometry.indices) {- const buffer = typeof geometry.indices === 'string' ? onGeometry.buffers[geometry.indices] : geometry.indices;- if (!buffer || buffer.type !== 'u32' || !buffer.data || buffer.file)- throw new RangeError('scatter requires inline u32 indices');- if ((buffer.offset ?? 0) !== 0 || buffer.count != null)- throw new RangeError('inline scatter buffers cannot have offset/count');- const rows = Array.from(buffer.data, numbers);- if (!rows.every(row => row.length === 1))- throw new RangeError('scatter indices require scalar elements');- indices = rows.flat();- }- else- indices = Array.from({ length: positions.length / 3 }, (_, i) => i);- if (indices.length % 3 !== 0 || !indices.every(i => Number.isInteger(i) && i >= 0 && i < positions.length / 3))- throw new RangeError('scatter indices require complete triangles of valid vertex indices');- const vertex = (i) => positions.slice(i * 3, i * 3 + 3);- const sub = (a, b) => a.map((v, k) => v - b[k]);- const triangles = [];- let area = 0;- for (let i = 0; i < indices.length; i += 3) {- const a = vertex(indices[i]), b = vertex(indices[i + 1]), c = vertex(indices[i + 2]);- const normal = cross(sub(b, a), sub(c, a)), weight = Math.hypot(...normal) / 2;- if (!Number.isFinite(weight))- throw new RangeError('scatter triangle area is not finite');- if (weight === 0)- continue;- area += weight;- if (!Number.isFinite(area))- throw new RangeError('scatter surface area is not finite');- triangles.push({ a, b, c, normal: unit(normal), end: area });- }- if (area === 0)- throw new RangeError('scatter requires nonzero surface area');- const transforms = [];- for (let i = 0; i < count; i++) {- const target = random() * area;- let lo = 0, hi = triangles.length - 1;- while (lo < hi) {- const mid = (lo + hi) >>> 1;- if (triangles[mid].end <= target)- lo = mid + 1;- else- hi = mid;- }- const { a, b, c, normal } = triangles[lo];- const u = Math.sqrt(random()), v = random();- const p = a.map((x, k) => x * (1 - u) + b[k] * u * (1 - v) + c[k] * u * v);- const reference = Math.abs(normal[0]) < Math.abs(normal[2]) ? [1, 0, 0] : [0, 0, 1];- const right = unit(cross(normal, reference)), forward = cross(right, normal);- transforms.push([...right, 0, ...normal, 0, ...forward, 0, ...p, 1]);- }- return finish(name, transforms);-}-const stdFunctions = {"box": {keys:["name","size"], required:[], invoke: args => (({name,...options}) => box(name,options))(args)},"sphere": {keys:["name","radius","segments","rings"], required:[], invoke: args => (({name,...options}) => sphere(name,options))(args)},"cylinder": {keys:["name","radius","height","segments"], required:[], invoke: args => (({name,...options}) => cylinder(name,options))(args)},@@ -626,8 +479,7 @@ const stdFunctions = {"box": {keys:["name","size"], required:[], invoke: args =>"capsule": {keys:["name","radius","height","segments","rings"], required:[], invoke: args => (({name,...options}) => capsule(name,options))(args)},"rounded_box": {keys:["name","size","radius","segments"], required:[], invoke: args => (({name,...options}) => roundedBox(name,options))(args)},"grid": {keys:["name","size","segments"], required:[], invoke: args => (({name,...options}) => grid(name,options))(args)},-"revolve": {keys:["name","profile","segments"], required:["profile"], invoke: args => (({name,...options}) => revolve(name,options))(args)},-"scatter": {keys:["on_geometry","count","seed","name"], required:["on_geometry","count","seed"], invoke: args => scatter(args["on_geometry"],args["count"],args["seed"],args["name"])}};+"revolve": {keys:["name","profile","segments"], required:["profile"], invoke: args => (({name,...options}) => revolve(name,options))(args)}};function stdEvaluate(name,args) {if (!Object.hasOwn(stdFunctions,name)) throw new Error('unknown standard-library function '+name+'; see vork help std');const fn=stdFunctions[name];diff --git a/crates/vork-std/tests/fonts/LiberationSans-Regular.ttf b/crates/vork-std/tests/fonts/LiberationSans-Regular.ttfnew file mode 100644index 0000000..7769c41Binary files /dev/null and b/crates/vork-std/tests/fonts/LiberationSans-Regular.ttf differdiff --git a/crates/vork-std/tests/fonts/OFL.txt b/crates/vork-std/tests/fonts/OFL.txtnew file mode 100644index 0000000..972d516--- /dev/null+++ b/crates/vork-std/tests/fonts/OFL.txt@@ -0,0 +1,107 @@+Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/+Upstream-Name: Liberation Fonts+Source: https://github.com/liberationfonts++Files: *+Copyright:+ Digitized data copyright (c) 2010 Google Corporation with Reserved Font Arimo, Tinos and Cousine.+ Copyright (c) 2012 Red Hat, Inc. with Reserved Font Name Liberation.+License: SIL-OFL-1.1+ This Font Software is licensed under the SIL Open Font License,+ Version 1.1.+ .+ This license is copied below, and is also available with a FAQ at:+ http://scripts.sil.org/OFL+ .+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+ .+ PREAMBLE The goals of the Open Font License (OFL) are to stimulate+ worldwide development of collaborative font projects, to support the font+ creation efforts of academic and linguistic communities, and to provide+ a free and open framework in which fonts may be shared and improved in+ partnership with others.+ .+ The OFL allows the licensed fonts to be used, studied, modified and+ redistributed freely as long as they are not sold by themselves.+ The fonts, including any derivative works, can be bundled, embedded,+ redistributed and/or sold with any software provided that any reserved+ names are not used by derivative works. The fonts and derivatives,+ however, cannot be released under any other type of license. The+ requirement for fonts to remain under this license does not apply to+ any document created using the fonts or their derivatives.+ .+ .+ .+ DEFINITIONS+ "Font Software" refers to the set of files released by the Copyright+ Holder(s) under this license and clearly marked as such.+ This may include source files, build scripts and documentation.+ .+ "Reserved Font Name" refers to any names specified as such after the+ copyright statement(s).+ .+ "Original Version" refers to the collection of Font Software components+ as distributed by the Copyright Holder(s).+ .+ "Modified Version" refers to any derivative made by adding to, deleting,+ or substituting ? in part or in whole ?+ any of the components of the Original Version, by changing formats or+ by porting the Font Software to a new environment.+ .+ "Author" refers to any designer, engineer, programmer, technical writer+ or other person who contributed to the Font Software.+ .+ .+ PERMISSION & CONDITIONS+ .+ Permission is hereby granted, free of charge, to any person obtaining a+ copy of the Font Software, to use, study, copy, merge, embed, modify,+ redistribute, and sell modified and unmodified copies of the Font+ Software, subject to the following conditions:+ .+ 1) Neither the Font Software nor any of its individual components,in+ Original or Modified Versions, may be sold by itself.+ .+ 2) Original or Modified Versions of the Font Software may be bundled,+ redistributed and/or sold with any software, provided that each copy+ contains the above copyright notice and this license. These can be+ included either as stand-alone text files, human-readable headers or+ in the appropriate machine-readable metadata fields within text or+ binary files as long as those fields can be easily viewed by the user.+ .+ 3) No Modified Version of the Font Software may use the Reserved Font+ Name(s) unless explicit written permission is granted by the+ corresponding Copyright Holder. This restriction only applies to the+ primary font name as presented to the users.+ .+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+ Software shall not be used to promote, endorse or advertise any+ Modified Version, except to acknowledge the contribution(s) of the+ Copyright Holder(s) and the Author(s) or with their explicit written+ permission.+ .+ 5) The Font Software, modified or unmodified, in part or in whole, must+ be distributed entirely under this license, and must not be distributed+ under any other license. The requirement for fonts to remain under+ this license does not apply to any document created using the Font+ Software.+ .+ .+ .+ TERMINATION+ This license becomes null and void if any of the above conditions are not met.+ .+ .+ .+ DISCLAIMER+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER+ DEALINGS IN THE FONT SOFTWARE.+ .+diff --git a/deny.toml b/deny.tomlindex c1598e0..a13234b 100644--- a/deny.toml+++ b/deny.toml@@ -1,4 +1,18 @@# Project licence selection is deliberately independent of dependency licences.+[advisories]+ignore = [+ # paste 1.0.15 is used only as a compile-time identifier-generating proc macro+ # by pulp 0.22.3, for the vendored exr 1.74.2 DWA SIMD decoder. It does not+ # parse EXR input at runtime. The current pulp release still uses paste;+ # pastey is not an upstream dependency upgrade: adopting it here requires+ # maintaining a pulp fork/patch or replacing the decoder stack (including+ # our EXR allocation bounds patch). Keep the existing code rather than add+ # that maintenance for an unmaintained-only advisory with no reported flaw.+ # Revisit when pulp removes paste or an EXR upgrade removes this dependency.+ { id = "RUSTSEC-2024-0436", reason = "Compile-time paste through pulp/exr; no upstream upgrade removes it without a local fork" },++]+[licenses]confidence-threshold = 0.8allow = ["MIT", "MIT-0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC", "Zlib", "0BSD", "CC0-1.0", "Unicode-3.0", "Unlicense", "LicenseRef-vork-Preview"]diff --git a/dist/example-payload.txt b/dist/example-payload.txtnew file mode 100644index 0000000..3a0a5bd--- /dev/null+++ b/dist/example-payload.txt@@ -0,0 +1,200 @@+# Exact example source files shared by archives and public source export.+# Downloaded/generated runtime assets do not belong in this list.+examples/assets/CC-BY-4.0.txt+examples/assets/CC0-1.0.txt+examples/assets/LicenseRef-LegalMark-Cesium.txt+examples/assets/README.md+examples/assets/forest_slope_1k.hdr+examples/black-hole/README.md+examples/black-hole/assets/.gitignore+examples/black-hole/assets/corinth/README.md+examples/black-hole/assets/corinth/bounds.json+examples/black-hole/assets/corinth/lambert10SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert10SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert10SG_normal.jpg+examples/black-hole/assets/corinth/lambert11SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert11SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert11SG_normal.jpg+examples/black-hole/assets/corinth/lambert13SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert13SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert13SG_normal.jpg+examples/black-hole/assets/corinth/lambert14SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert14SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert16SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert16SG_emissive.jpg+examples/black-hole/assets/corinth/lambert16SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert16SG_normal.jpg+examples/black-hole/assets/corinth/lambert17SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert17SG_emissive.jpg+examples/black-hole/assets/corinth/lambert17SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert17SG_normal.jpg+examples/black-hole/assets/corinth/lambert18SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert18SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert18SG_normal.jpg+examples/black-hole/assets/corinth/lambert2SG_baseColor.png+examples/black-hole/assets/corinth/lambert2SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert2SG_normal.jpg+examples/black-hole/assets/corinth/lambert6SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert6SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert6SG_normal.jpg+examples/black-hole/assets/corinth/lambert7SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert7SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert7SG_normal.jpg+examples/black-hole/assets/corinth/lambert8SG_baseColor.jpg+examples/black-hole/assets/corinth/lambert8SG_emissive.jpg+examples/black-hole/assets/corinth/lambert8SG_metallicRoughness.jpg+examples/black-hole/assets/corinth/lambert8SG_normal.jpg+examples/black-hole/assets/corinth/license.txt+examples/black-hole/assets/corinth/scene.bin+examples/black-hole/assets/corinth/scene.gltf+examples/black-hole/disk.slang+examples/black-hole/environment.slang+examples/black-hole/generate.py+examples/black-hole/moon.slang+examples/black-hole/propagation.slang+examples/black-hole/render.sh+examples/black-hole/scene.json+examples/black-hole/scene.profile.json+examples/black-hole/scene.std.bin+examples/black-hole/test_geodesics.py+examples/cake/CREDITS.md+examples/cake/README.md+examples/cake/assets.lock.json+examples/cake/prepare.py+examples/cake/scene.json.in+examples/compositor-effects/README.md+examples/compositor-effects/chromatic-dispersion.slang+examples/compositor-effects/glare-fog-glow.json+examples/compositor-effects/glare-fog-glow.profile.json+examples/compositor-effects/glare-ghosts.json+examples/compositor-effects/glare-ghosts.profile.json+examples/compositor-effects/glare-simple-star.json+examples/compositor-effects/glare-simple-star.profile.json+examples/compositor-effects/glare-streaks.json+examples/compositor-effects/glare-streaks.profile.json+examples/compositor-effects/glare.slang+examples/compositor-effects/highlight.slang+examples/compositor-effects/vignette.slang+examples/compositor_graph.py+examples/first-scene.json+examples/kitchen/CREDITS.md+examples/kitchen/README.md+examples/kitchen/look/kitchen_surface.slang+examples/kitchen/look/materials.json.in+examples/kitchen/look/palette_007df2d033bd6150.exr+examples/kitchen/look/palette_01647080d73a95c4.exr+examples/kitchen/look/palette_11c8d576d0d94b3b.exr+examples/kitchen/look/palette_129a7701cd353a30.exr+examples/kitchen/look/palette_1e4cae3fb0206445.exr+examples/kitchen/look/palette_2267e62bbc967c20.exr+examples/kitchen/look/palette_37b242c20cfce5f1.exr+examples/kitchen/look/palette_382353968e6e0546.exr+examples/kitchen/look/palette_389abd3a162a9920.exr+examples/kitchen/look/palette_3c7d7f19b57e3828.exr+examples/kitchen/look/palette_43d30becaf9c1544.exr+examples/kitchen/look/palette_46994d7603846568.exr+examples/kitchen/look/palette_46f2c1b81d64f595.exr+examples/kitchen/look/palette_4997ef5b8aedb934.exr+examples/kitchen/look/palette_555fe47cf4fc0262.exr+examples/kitchen/look/palette_5572e71220b85d41.exr+examples/kitchen/look/palette_57ee68d6b3b1429a.exr+examples/kitchen/look/palette_68167fe92a009a31.exr+examples/kitchen/look/palette_688664c387156e11.exr+examples/kitchen/look/palette_6ab581bf3861568f.exr+examples/kitchen/look/palette_74de7e0800f7a640.exr+examples/kitchen/look/palette_75bb982a4eae0919.exr+examples/kitchen/look/palette_7ba9bbb4b85fbeaf.exr+examples/kitchen/look/palette_7e1d95d1c067d18c.exr+examples/kitchen/look/palette_8d44b05bbfea45ad.exr+examples/kitchen/look/palette_8f2317f850570573.exr+examples/kitchen/look/palette_935dd694c2b5edfa.exr+examples/kitchen/look/palette_96b5ec9623b66b07.exr+examples/kitchen/look/palette_9ddb7f9a28fa1734.exr+examples/kitchen/look/palette_9de6c5c02b6e0c0a.exr+examples/kitchen/look/palette_ae741cc62aeb4331.exr+examples/kitchen/look/palette_aeee79c541473870.exr+examples/kitchen/look/palette_b52cc54e9059afbd.exr+examples/kitchen/look/palette_c0a4cd16ccbe1629.exr+examples/kitchen/look/palette_c174196c22bb7085.exr+examples/kitchen/look/palette_c8d37b92436cd081.exr+examples/kitchen/look/palette_ce2dd346ae378611.exr+examples/kitchen/look/palette_ce9abef449fcaa56.exr+examples/kitchen/look/palette_daaa598ae0d7262a.exr+examples/kitchen/look/palette_dafa503e506377c8.exr+examples/kitchen/look/palette_dcacf66da5f49542.exr+examples/kitchen/look/palette_df99e0e643fb2cf4.exr+examples/kitchen/look/palette_e3a7d74f8298e644.exr+examples/kitchen/look/palette_e95c4dc86671a74e.exr+examples/kitchen/look/palette_ed0bacfe02751f63.exr+examples/kitchen/look/palette_f13f5020d45aef0c.exr+examples/kitchen/look/palette_f61dd38931ecfcc4.exr+examples/kitchen/look/palette_f7e35696f55eb3c4.exr+examples/kitchen/look/palette_fa40d1bec53875b2.exr+examples/kitchen/prepare.py+examples/murmuration/CREDITS+examples/murmuration/README.md+examples/murmuration/assets.lock.json+examples/murmuration/assets/.gitignore+examples/murmuration/assets/birds/birds.bin+examples/murmuration/assets/birds/birds.json+examples/murmuration/assets/birds/crow-normal.png+examples/murmuration/assets/birds/crow.png+examples/murmuration/assets/birds/starling-normal.png+examples/murmuration/assets/birds/starling.jpg+examples/murmuration/launch/advance.slang+examples/murmuration/launch/clear.slang+examples/murmuration/launch/dusk-weight.exr+examples/murmuration/launch/flight.slang+examples/murmuration/launch/grid.slang+examples/murmuration/launch/hero.slang+examples/murmuration/launch/initialize.slang+examples/murmuration/launch/lod-count-skim.slang+examples/murmuration/launch/lod-pack.slang+examples/murmuration/launch/lod-prefix.slang+examples/murmuration/launch/place.slang+examples/murmuration/launch/sand.slang+examples/murmuration/launch/silhouette.slang+examples/murmuration/launch/skim.json.in+examples/murmuration/launch/vegetation.slang+examples/murmuration/prepare_launch.py+examples/vfx-artifact/README.md+examples/vfx-artifact/assets.json+examples/vfx-artifact/build.py+examples/vfx-artifact/capture.slang+examples/vfx-artifact/combine.slang+examples/vfx-artifact/depth.py+examples/vfx-artifact/finish.slang+examples/vfx-artifact/halo.slang+examples/vfx-artifact/mattes.py+examples/vfx-artifact/prepare.py+examples/vfx-artifact/ratio.slang+examples/vfx-artifact/render.py+examples/vfx-artifact/skin.slang+examples/vfx-artifact/track.py+examples/vfx-artifact/verify_lock.py+examples/vfx-neon/README.md+examples/vfx-neon/assets.json+examples/vfx-neon/author.py+examples/vfx-neon/beacon.py+examples/vfx-neon/camera.py+examples/vfx-neon/composite.slang+examples/vfx-neon/matchmove/ecc.py+examples/vfx-neon/matchmove/ecc_bundle.py+examples/vfx-neon/matchmove/planar_bundle.py+examples/vfx-neon/matchmove/refit.py+examples/vfx-neon/matchmove/solve.py+examples/vfx-neon/matchmove/track_dense.py+examples/vfx-neon/prepare.py+examples/vfx-neon/requirements.txt+examples/vfx-neon/reveal.py+examples/vfx-neon/reveal.slang+examples/vfx-neon/review.py+examples/vfx-neon/wet.slang+examples/water/README.md+examples/water/bowl.slang+examples/water/ceramic.slang+examples/water/make_scene.py+examples/water/prepare_snapshot.py+examples/water/scene.json+examples/water/scene.std.bin+examples/water/table.slangdiff --git a/docs/BUILD.md b/docs/BUILD.mdnew file mode 100644index 0000000..ff89a32--- /dev/null+++ b/docs/BUILD.md@@ -0,0 +1,160 @@+# Build from source++Run these commands from the checkout root. Source builds need Rust, a native+C/C++ toolchain, Python with safe tar extraction filters, and the pinned Slang+compiler. Cargo does not download Slang. The supported Unix toolchain archives+are Apple Silicon macOS and x86-64 Linux (see `dist/slang.json`); there is no+pinned Intel Mac or Linux ARM archive.++## Prerequisites++The pinned Slang 2026.20 macOS binaries target macOS 26. Older macOS versions+have not been qualified with this toolchain.++On macOS, install Apple's command line tools, then install Homebrew from+https://brew.sh if it is not already available:++```sh+xcode-select --install+```++Finish that installer before continuing. Use Homebrew Python explicitly:+stock macOS Python 3.9 may lack the extraction filters required by the Slang+installer. No pip packages are needed.++```sh+brew install [email protected]+PYTHON="$(brew --prefix [email protected])/bin/python3.12"+```++On Ubuntu 24.04 x86-64 (the Linux baseline), install:++```sh+sudo apt-get update+sudo apt-get install -y build-essential pkg-config libclang-dev curl git python3 ca-certificates+PYTHON=python3+```++Basis texture bindings require libclang (`libclang-dev` on Ubuntu; supplied+by Apple's command line tools on macOS). If bindgen cannot find it, set+`LIBCLANG_PATH` to the directory containing libclang.++Other Linux distributions need equivalent C/C++ build tools, libclang and Python 3.12++(or a Python release with backported `tarfile.data_filter`). Rendering also+needs a working Vulkan driver; building and GPU-free commands do not need a GPU.+For your own NVIDIA Linux machine, a [Docker runtime](REMOTE-GPU.md) is available.++Install Rust 1.96, matching CI, through rustup (https://rustup.rs):++```sh+curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs -o /tmp/vork-rustup.sh+sh /tmp/vork-rustup.sh -y --default-toolchain 1.96+. "$HOME/.cargo/env"+```++## Install Slang and build++Clone the repository if needed, then enter it.++Choose a new, empty destination outside the checkout. The installer downloads+and verifies the archive against `dist/slang.json`, and refuses to overwrite+an existing directory. Keep the entire toolchain, including its libraries,+modules and notices, together.++```sh+"$PYTHON" scripts/install-slang "$HOME/.local/share/vork/slang-2026.20"+export VORK_SLANGC="$HOME/.local/share/vork/slang-2026.20/bin/slangc"+"$VORK_SLANGC" -version+cargo +1.96 build --release --workspace --locked+./target/release/vork --help+./target/release/vork help+```++The build compiles shaders for both Vulkan and Metal on either host. It checks+the Slang version against the pin. `VORK_SLANGC` must be an absolute executable+path; alternatively the build can find the pinned `slangc` on `PATH`. Export+`VORK_SLANGC` again in each new shell, or add the export to your shell startup+file. A `cannot start slangc` error means this setup is missing; a version+mismatch means a different compiler was selected.++The binary is `target/release/vork`, or `$CARGO_TARGET_DIR/release/vork` when+that environment variable is set. These commands do not install it globally.+Runtime program compilation also needs Slang; retain the export when running+the binary from the build directory.++## Rendering and test dependencies++Start with `vork help` and the scenes in `examples/`. macOS uses Metal; Linux+uses Vulkan. Install FFmpeg/ffprobe for video commands and encoding tests+(`brew install ffmpeg` on macOS, `sudo apt-get install ffmpeg` on Ubuntu).++The public workspace includes CPU unit tests and small fixtures. The text tests+use the bundled Liberation Sans font under SIL OFL 1.1; its copyright and licence+are in `crates/vork-std/tests/fonts/OFL.txt`. Renderer fixtures are synthetic scene,+shader and glTF inputs shipped with the source. No asset downloads are needed to+run the default tests. Corpus-dependent tests that require unshipped assets are+excluded from the public source; they are not part of its test coverage.++Renderer GPU tests require the explicit runtime opt-in `VORK_GPU_TESTS=1`;+without it they print a skip diagnostic (visible with `-- --nocapture`).+CPU and numeric tests remain enabled. Tests marked ignored explain their additional requirements. GPU tests need a+supported Metal/Vulkan device, including ray-query support; a CPU-only test run+does not validate rendering. To run ignored tests after installing their stated+dependencies, set `VORK_GPU_TESTS=1` and use+`cargo test -p vork-render -p vork-cli -- --include-ignored --nocapture`.++OIDN is loaded at runtime, not required to compile. For denoised renders and+GPU tests that exercise denoising, install the pinned runtime with the same Python:++```sh+"$PYTHON" scripts/install-oidn "$HOME/.local/share/vork/oidn"+# macOS:+export VORK_OIDN="$HOME/.local/share/vork/oidn/lib/libOpenImageDenoise.2.dylib"+# Linux (use this instead):+export VORK_OIDN="$HOME/.local/share/vork/oidn/lib/libOpenImageDenoise.so.2"+```++Workspace tests additionally need Node.js/npm for generated SDK checks.+Install the TypeScript dependencies and fetch the locked crate sources for the+licence notice check, then check and test every public workspace target:++```sh+npm ci --prefix packages/ts+cargo +1.96 fetch --locked+cargo +1.96 check --workspace --all-targets --locked+cargo +1.96 test --workspace --locked+```++Use `-- --nocapture` to see test diagnostics, including any GPU test skipped when+adapter discovery finds no device. Missing fixtures, missing required tools and+failed assertions are failures. An ignored or skipped GPU test supplies no GPU+coverage.++See [README installation](../README.md#install) for binary installation and runtime+setup, and `vork help programs --all` for authored Slang programs. Node/npm and the+SDKs are not prerequisites for the Rust workspace build.++++## Public workflows++Distribution archives are built privately and attached to public GitHub releases.+For source validation, run the workspace tests above and `npm ci && npm test`+in `packages/ts`. Rendering checks need the runtime dependencies above;+run the examples with a supported GPU and inspect the resulting frames.++## Release shader assets++Hosted distribution jobs run `scripts/prepare-shaders` with the final binary+(after macOS signing). It invokes the hidden `prepare-release-shaders` command:+the ordinary setup catalogue and Slang compiler run against a no-op wgpu device,+without opening a GPU driver, OIDN device or executing shaders. Denoiser+preparation constructs only the renderer's pack/unpack pipelines. macOS emits Metal source;+Linux and Windows emit SPIR-V. The bundle excludes all driver cache entries+and is bound to the packaged binary's SHA-256. `scripts/package-release` refuses+to package without this verified bundle. `vork setup` on the user's real GPU+then warms its own driver cache from those portable assets.++`check-release --skip-setup --skip-render` verifies installation, compiler and+portable assets on GPU-free hosted runners. Installed rendering, video and+denoising still require the real-device acceptance check.diff --git a/docs/REMOTE-GPU.md b/docs/REMOTE-GPU.mdnew file mode 100644index 0000000..e40065b--- /dev/null+++ b/docs/REMOTE-GPU.md@@ -0,0 +1,53 @@+# Run on your own NVIDIA GPU++Rendering requires Apple Silicon or an NVIDIA GPU with Vulkan ray queries.+Authoring scenes and `vork help` do not need a GPU. Docker requires a suitable+GPU on its host; it does not provide one. Hosted rendering: details will be+added here when available.++The Docker runtime below targets your own Linux x86-64 NVIDIA machine. Use a+matching Linux release archive and SHA256 from its `SHA256SUMS`. There is no+official registry image to pull yet. See [BUILD.md](BUILD.md) for source builds.+Put scene.json and all its assets in the job directory, keeping relative paths.++## Docker on an NVIDIA host++Use Linux x86-64 with a supported NVIDIA driver and the+[NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html).+The host supplies its NVIDIA libraries; do not install a mismatched driver in+the image. Docker Desktop on a Mac does not expose Metal to a Linux container.+WSL2 GPU support is a separate host configuration and has not been validated here.++```sh+python3 tools/gpu/prepare.py --bundle /path/to/vork-0.2.0-linux-x64.tar.gz \+ --sha256 RELEASE_SHA256 --context /tmp/vork-image-context+docker build --platform linux/amd64 -t vork-gpu:local /tmp/vork-image-context+docker run --rm --gpus all vork-gpu:local vork setup+docker run --rm --gpus all \+ -v /absolute/job:/job:ro -v /absolute/results:/results \+ vork-gpu:local vork render scene.json --out /results/video.mp4 --profile std/draft+```++Create the results directory first. The image runs as root by default; use+`--user "$(id -u):$(id -g)" -e VORK_CACHE_DIR=/tmp/vork-cache` on Linux+for your own output ownership. It needs a+writable `/tmp` and cache directory. Mount a writable directory and set+`VORK_CACHE_DIR` to reuse caches across containers; never share a writable cache+between mutually untrusted users.++The entrypoint creates a private temporary manifest pointing at+`libEGL_nvidia.so.0` and sets both `VK_DRIVER_FILES` and `VK_ICD_FILENAMES`.+A read-only NVIDIA manifest can point at `libGLX_nvidia.so.0`, which fails+in its headless environment. Rewriting `/etc/vulkan/icd.d` can also fail because+it is mounted read-only. This image leaves it alone. Do not bypass the entrypoint+when rendering. NVIDIA graphics, compute, utility and video capabilities are+requested; native NVENC handles MP4 encoding. FFmpeg is built with GPL/nonfree+features disabled and shared LGPL libraries, with matching source and notices+retained in `/opt/ffmpeg/notices`. There is no libx264 fallback in this image;+a working NVIDIA video encoder is required for H.264 video. This version's+`vork setup` can warn that libx264 is missing alongside its muxing message;+libx264 is not needed for native NVENC muxing. Setup exits successfully without libx264. Slang, OIDN, portable+shaders, the Preview License and all release notices accompany the executable.+The GPL Blender bridge is excluded. Ubuntu OS utilities retain their own+licenses, including GPL; the FFmpeg license check applies to its configured+binaries.diff --git a/docs/help/animation.md b/docs/help/animation.mdindex e682913..0439bf7 100644--- a/docs/help/animation.md+++ b/docs/help/animation.md@@ -15,3 +15,7 @@ cuts are inactive. Numeric nonstructural scene fields, including material and prAiming and object focus use evaluated poses at the requested time, includinginstallation and shutter samples. Unused base poses may coincide; coincidentevaluated aiming origins are errors naming the node and sample time.++Camera target is structural, including [x,y,z], and cannot be animated. Set+"target":"aim", add {"name":"aim","translation":[0,0,0]} to nodes, then track+["nodes","aim","translation"] with vector keys, e.g. [[0,[0,0,0]],[2,[1,0,0]]].diff --git a/docs/help/build.md b/docs/help/build.mdindex 9bd6d8d..b329cbd 100644--- a/docs/help/build.md+++ b/docs/help/build.md@@ -108,3 +108,37 @@ lib/libOpenImageDenoise.2.dylib on macOS, or bin/OpenImageDenoise.dll on WindowsNode/npm and the SDKs are not prerequisites for the Rust workspace build.For SDK setup use `vork help sdk`; for authored Slang use `vork help programs`.++## Workspace tests++Workspace tests additionally need Node.js/npm for generated SDK checks.+Install the TypeScript dependencies and fetch the locked crate sources for the+licence notice check. After installing Slang and FFmpeg/ffprobe, run from the+checkout root:++```sh+npm ci --prefix packages/ts+cargo +1.96 fetch --locked+cargo +1.96 check --workspace --all-targets --locked+cargo +1.96 test --workspace --locked+```++The public workspace tests use shipped synthetic fixtures and the bundled+Liberation Sans font (SIL OFL 1.1, including copyright and licence in+crates/vork-std/tests/fonts/OFL.txt). No additional asset downloads are needed.+Corpus-dependent tests requiring unshipped assets are excluded from the public+source and are not part of its coverage.++Renderer GPU tests require the explicit runtime opt-in `VORK_GPU_TESTS=1`;+without it they print a skip diagnostic (visible with `-- --nocapture`). CPU and+numeric tests remain enabled. Ignored tests state their extra requirements.+With a supported GPU and the runtime dependencies installed:++```sh+VORK_GPU_TESTS=1 cargo test -p vork-render -p vork-cli -- --include-ignored --nocapture+```++In PowerShell set `$env:VORK_GPU_TESTS = "1"` before the Cargo command.+Use `-- --nocapture` on the default tests to see diagnostics, including skips+when adapter discovery finds no GPU. Ignored and skipped tests supply no GPU+coverage. Denoising tests also need the pinned OIDN runtime described above.diff --git a/docs/help/cameras.md b/docs/help/cameras.mdindex 8b1abed..8bd959e 100644--- a/docs/help/cameras.md+++ b/docs/help/cameras.md@@ -1,7 +1,8 @@CAMERAS-camera.material selects a ray program; omitted selects std/camera. Its numeric Inputs use material tracks.-std/camera follows Blender physical cameras: projection, fit, lens, sensor_width/height, ortho_scale, shift, clip_start/end, use_dof, focus_distance and aperture_* are Inputs.+camera.material selects a ray program; omitted selects std/camera. Its numeric Inputs use material tracks. An explicit material must name program:"std/camera"; omission on a material selects std/openpbr.+std/camera follows Blender physical cameras. Input fields below use material.inputs; lens and sensor sizes are mm, clip/focus/ortho_scale metres, aperture_rotation radians. Exact lookup: vork help field std/camera.lens.focus_object supplies sampled camera-axis depth; target and transforms retain node semantics.<!-- all -->CAMERA PROGRAM REFERENCE+Physical apertures can select sampled path transport where supported, retaining the selected profile's sample budget.CameraRay t_min/t_max bound geometry visibility in metres along its normalized direction. Optional camera_calibration declares projective acceleration; omission declares none. See light-paths and camera-json.diff --git a/docs/help/compositor.md b/docs/help/compositor.mdindex 2bce121..2ca1691 100644--- a/docs/help/compositor.md+++ b/docs/help/compositor.md@@ -2,11 +2,16 @@ COMPOSITORrender.compositor: ordered material-name|{material,name?,resolution?} entries; last image is output; material may be inline.resolution: [width,height] or positive output scale (floor, minimum 1); omitted = output; final image resampled to output.Image bindings: {node:earlier-name}, {image:name}, {channel:color|depth|view_normal|object_index|motion|shadow_catcher}, {aov:name}; names are local to each graph.+For bloom, add these two entries to render.compositor:+ {"name":"highlights","material":{"program":"std/bloom","inputs":{"stage":"prepare","original":{"channel":"color"}}}},+ {"material":{"program":"std/bloom","inputs":{"stage":"combine","original":{"channel":"color"},"source":{"node":"highlights"}}}}+This one-level bloom preserves alpha; adjust threshold on prepare and strength on combine.+the authored glare example (examples/compositor-effects/glare.slang) reads the previous compositor result (first entry reads beauty); no Image input. Returns additive glare; merge with the original in a later entry.<!-- all -->COMPOSITOR PROGRAM REFERENCEfloat4 composite(CompositeContext,Inputs): scene-linear premultiplied RGBA; compositor_sample(uv) reads previous result (first reads accumulated beauty).compositor_sample(image,uv): clamped bilinear; compositor_load(image,int2): clamped pixel; compositor_size(image): pixels; compositor_size() reads previous extent. UV origin top left; ctx.size is working extent.-Runs after shutter accumulation/denoising, before exposure/display. No history. std/bloom stages: prepare/downsample/upsample/combine; post/glare returns additive RGBA for a separate merge.+Runs after shutter accumulation/denoising, before exposure/display. No history. std/bloom stages: prepare/downsample/upsample/combine; the authored glare example (examples/compositor-effects/glare.slang) returns additive RGBA for a separate merge.std/bloom follows Blender bloom arithmetic through an explicit image pyramid; no stages or bindings are inserted automatically.Inputs (defaults): stage=combine (prepare|downsample|upsample|combine); original, source, fine are Image bindings with no default.@@ -23,3 +28,7 @@ threshold=1: nonnegative scene-linear highlight cutoff; smoothness=0.1: knee widclamp=false, maximum=10: optional nonnegative highlight-magnitude ceiling in prepare.strength=1, saturation=1, tint=[1,1,1]: nonnegative combine controls; strength=0 preserves the nonnegative original.Missing stage-required Image bindings are scene errors, including zero-strength combine nodes.++Copy the entire examples/compositor-effects directory; glare needs highlight.slang+next to it. The shipped glare-streaks.json demonstrates the additive merge graph.+See vork help upgrade for 0.1 program and Slang-import replacements.diff --git a/docs/help/diagnostics.md b/docs/help/diagnostics.mdindex 03e63e7..1933fd3 100644--- a/docs/help/diagnostics.md+++ b/docs/help/diagnostics.md@@ -1,3 +1,4 @@+Setup and render progress goes to stderr: a plain line every 5 seconds in terminals and redirected logs. Redirect both streams (`>run.log 2>&1`) for a complete log. Counts cover completed configurations/frames and compiler calls discovered so far; elapsed time is not an ETA.DIAGNOSTICS: --diagnostics writes NAME.timings.json (adapter, cache, GPU, encoder timings) andnon-finite pixel counts; with it, --no-write (no files) and --gpu-only (no readback) benchmark.Environment: VORK_CACHE_DIR, VORK_CACHE_BYTES (default 16 GiB; 0 = no disk cache), VORK_SLANGC,diff --git a/docs/help/errors.md b/docs/help/errors.mdindex 3a2c612..cc27da7 100644--- a/docs/help/errors.md+++ b/docs/help/errors.md@@ -1,3 +1,4 @@ERRORS: exit codes: 0 success; 2 usage; 3 invalid scene or program;4 device, GPU memory, encoder or setup; 5 filesystem IO.-Known issue in 0.1.0: truncating help through a pipe may panic with exit 101.+A stdout consumer closing its pipe early exits successfully. Other stdout write failures+are filesystem IO errors.diff --git a/docs/help/geometry.md b/docs/help/geometry.mdindex 7afdba6..b564978 100644--- a/docs/help/geometry.md+++ b/docs/help/geometry.md@@ -20,7 +20,7 @@ position = [(radius+tube*cos(b))*cos(a), (radius+tube*cos(b))*sin(a), tube*sin(bNormal = [cos(b)*cos(a), cos(b)*sin(a), sin(b)]; connect adjacent rings with triangles.Duplicate UV seams, cap partial arcs, and reverse winding for a negative sweep.Procedural materials: write a Slang surface program (vork help programs --all);-use world/object position and std/noise rather than loading a sample scene.+use world/object position and std/procedurals rather than loading a sample scene.<!-- all -->IMPLICIT SURFACE REFERENCEdiff --git a/docs/help/index.md b/docs/help/index.mdindex 25d7001..34299de 100644--- a/docs/help/index.md+++ b/docs/help/index.md@@ -3,26 +3,22 @@ Supported GPUs: Apple Silicon (Metal) and recent NVIDIA (Vulkan).Unknown fields are errors; omit anything at its default.FIRST IMAGE-Save this as shot.json:-```json-{"version":2,"nodes":[- {"type":"mesh","geometry":{"std":"sphere","radius":1},- "materials":[{"inputs":{"base_color":[0.12,0.35,0.65],"specular_roughness":0.3}}]},- {"type":"mesh","translation":[0,-1,0],"geometry":{"std":"grid","size":[10,10]},- "materials":[{"inputs":{"base_color":[0.35,0.35,0.35]}}]},- {"type":"light","shape":"rectangle","translation":[-3,5,4],"target":[0,0,0],- "energy":700,"size":4,"color":[1,0.92,0.8]},- {"type":"camera","translation":[3,2,5],"target":[0,0,0]}-],"render":{"resolution":[640,480]}}-```-vork render shot.json --out shot.png --profile std/previs+vork init my-shot+cd my-shot+vork render scene.json --out shot.png --profile std/draft+vork help+Creates an offline scene from sphere, box and grid primitives; no assets to fetch.+vork init [DIR] [--language json|typescript|python] (default DIR: ., language: json).+Always writes scene.json and README.md; language adds scene.ts or scene.py.+Existing files are never overwritten. Source authoring requires the matching SDK;+scene.json renders immediately. Edit the source, regenerate JSON, then render again.Inspect framing, scale and shadows. Adjust camera target, light position and material colour.-vork render shot.json --out shot.png --profile std/final+vork render scene.json --out shot.png --profile std/finalUse std/path for accurate indirect lighting, glass and caustics. For glass panes setgeometry_thin_walled: true. RGB background changes the backdrop, not the lighting.To import a textured model, replace the first mesh with{"type":"asset","name":"model","file":"model.glb"}. Keep .gltf files with their referenced buffers and textures.-Adjust the camera target and distance to the asset's size. Paths are relative to shot.json.+Adjust the camera target and distance to the asset's size. Paths are relative to scene.json.Supported features and known limits: vork help limits. Source builds: vork help build.@@ -65,6 +61,7 @@ COMMON FIELDS (advanced fields: vork help TOPIC --all; exact field: vork help fi<!-- generated-api:start -->Scene {+ $schema: string; editor schema URLanimation: layer[] = []buffers: {name:buffer} = {}geometry: {name:geometry} = {}@@ -81,7 +78,7 @@ Node {name: string = ""; globally unique, including imported nodesrotation: [x,y,z,w] quaternion | {euler:[x,y,z]} (Blender XYZ) = [0,0,0,1]scale: [x,y,z] = [1,1,1]; any zero world-scale component hides geometry, including children- target: node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top+ target: node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translationtranslation: [x,y,z] = [0,0,0]; parent framevisible: bool = true; false hides the subtree and disables its lights; animatable (step)visible_camera: bool = true@@ -90,7 +87,7 @@ Node {Mesh (type: mesh) {geometry: geometry-name|inline geometry- materials: (material-name|inline material)[] = []; empty = default std/openpbr with roughness 0.5+ materials: (material-name|inline material)[] = []; empty = default std/openpbr with roughness 0.3}Asset (type: asset) {@@ -144,7 +141,7 @@ Asset nodes also take materials and nodes overrides (vork help nodes).LIBRARIESStd builders return {buffers,geometry}; author loaders expand {std: NAME, ...options} before scene decoding.Shapes are centred; dimensions are metres. Inline geometry uses {std: NAME, ...options}.-Common builders (all shapes, text, extrusion and scatter: vork help std --all):+Common builders (all shapes, text and extrusion: vork help std --all):<!-- generated-shapes:start -->box: {name?:string="box",size?:vec3=[2,2,2]} → GeometryFragmentsphere: {name?:string="sphere",radius?:number=1,segments?:number=32,rings?:number=16} → GeometryFragment@@ -156,6 +153,7 @@ Environment: light.material evaluates radiance; std/environment_image reads ordivork std environment preprocesses HDR lighting; vork std sky declares atmosphere and an ordinary sun.Topics (vork help TOPIC [--all]):+upgrade: breaking changes and replacements by releasecontract: when scenes are validated; what is fixed after installnodes: glTF asset overrides and imported-node addresses, skins, morph targets, object ID assignmentcameras: sampled depth of field; OpenCV export@@ -176,8 +174,12 @@ sdk: TypeScript and Python helpersstd: full std/sky and std/hair inputs; Slang modules (noise, ramps, bump)blender: Filmic display, Blender node functions for Slangfluid: APIC/FLIP liquid, Yu–Turk surfaces, wetting and whitewater-post: glare, vignette, lens distortion and white balance inputs+post: white balance colour adaptation inputserrors: exit codesdiagnostics: timing files, benchmark flags, environment variableslimits: supported hardware, lighting approximations and scene-size limitsbuild: source prerequisites, pinned toolchains and tests on macOS, Linux and Windows++Scene JSON supports `"$schema": "https://voyager.so/vork/schema/scene.schema.json"` for editor+completion and validation. `vork init` and SDK scene writers include it; vork+accepts this metadata without fetching it or changing the render.diff --git a/docs/help/init.md b/docs/help/init.mdnew file mode 100644index 0000000..7a775f1--- /dev/null+++ b/docs/help/init.md@@ -0,0 +1,10 @@+INIT+vork init [dir] [--language json|typescript|python]+Create a starter project in dir (default: current directory), without network or GPU access.+Writes scene.json and README.md. Existing output files cause a refusal before writing;+unrelated files are preserved. scene.json renders immediately:+ vork render scene.json --profile std/draft --out render.png++JSON is the default. TypeScript adds scene.ts and a package.json with type: module;+Python adds scene.py. README.md explains how to install the matching bundled SDK+and regenerate scene.json. See vork help sdk for SDK details.diff --git a/docs/help/limits.md b/docs/help/limits.mdindex f2ab991..c64826a 100644--- a/docs/help/limits.md+++ b/docs/help/limits.md@@ -3,11 +3,14 @@ Supported GPUs: Apple Silicon Metal and recent NVIDIA Vulkan with hardware raytracing and storage buffer arrays. AMD, Intel and CPU/software rendering areunsupported. Run vork setup to check the adapter. Windows x64 ships install.ps1;macOS and Linux provide install.sh as a separate release asset.-The 0.1.0 bundled Slang toolchain targets macOS 26; older macOS is unqualified.+The 0.2 bundled Slang toolchain targets macOS 26; older macOS is unqualified.See README.md (Mac) for each companion binary's deployment target. See README.md (Install) for binary setup.Participating media (fog, smoke and volumes) are absent from this release's API.-Legacy medium bindings are ignored with a warning; surface subsurface scattering+The removed std/fog, blender/principled_volume and blender.volume programs fail+with unknown-program errors, including unused material definitions. Remove those+definitions and medium-only nodes/bindings; see vork help upgrade. Other legacy+medium bindings may be ignored with a warning. Surface subsurface scatteringis supported.std/final approximates indirect lighting and can darken interiors, including glossy@@ -45,4 +48,7 @@ displacement on computed/implicit geometry and normal-dependent point displacemeare ignored. Computed instance material attributes retain authored values.Legacy spatial environments evaluate at the origin. Extra environment lights andunsupported light masks are ignored with warnings. Environment programs sampling-render images fall back to the light colour. Inspect warnings and the image.+render images fall back to the light colour. Inspect warnings and the image. Each dropped effect prints WARNING: REQUESTED EFFECT DROPPED,+with its code, authored request and omitted/substituted behaviour. Every render+meta.json sidecar and SDK render result returns the same structured warnings array;+warning-and-render success does not mean every requested effect was applied.diff --git a/docs/help/nodes.md b/docs/help/nodes.mdindex cf9c90f..af3cd29 100644--- a/docs/help/nodes.md+++ b/docs/help/nodes.md@@ -5,6 +5,7 @@ Assets load .glb/.gltf. Imported names: asset/node-name or asset/#index.Imported joints are not target, focus or attachment addresses.<!-- all -->+Painted backdrops: disable visible_shadow; disable other ray visibility when the card should appear only to the camera.FROM BLENDERY-up: Blender (x,y,z) -> vork (x,z,-y). Euler is Blender XYZ order about vork axes; a Blender Zturn is vork Y. Lights and cameras aim local -Z, so identity is horizontal; aim with target.diff --git a/docs/help/outputs.md b/docs/help/outputs.mdindex a945762..ebc1929 100644--- a/docs/help/outputs.md+++ b/docs/help/outputs.md@@ -1,13 +1,13 @@OUTPUT ENCODINGS-.png one still (t=0 unless --at); other channels beside it as NAME.<channel>.png+.png RGBA still (keeps alpha; use render.background "transparent"); t=0 unless --at; other channels beside it as NAME.<channel>.pngPNG filename frame patterns (two or more # characters or printf-style %d/%04d) are usage errors; use a directory or %06d.exr for frames. Parent directories and other filename characters are literal.directory (no extension or trailing /): NNNNNN.png frames plus channel PNGsPATH/%06d.exr: one multilayer OpenEXR per frame, scene-linear premultiplied, before exposure.mp4 H.264; .mov ProRes 4444 RGBA (keeps alpha; transparency needs render.background "transparent")--at SECONDS: one still; needs .png, directory or EXR. --frame-start/--frame-end N: inclusiveabsolute frame indices, default the whole clip; not with --at.-Sidecars: OUT.meta.json for each --out OUT, e.g. check.png.meta.json (fps, per-frame camera and depth unit, object_ids pass_index -> node,-exposure); OUT.camera.json when camera is a channel (videos always; vork help camera-json).+Sidecars: OUT/meta.json for directories; OUT.meta.json for files, e.g. check.png.meta.json (fps, per-frame camera and depth unit, object_ids pass_index -> node,+exposure, warnings [{code,requested,dropped}] for omitted/substituted effects); camera.json in directories or OUT.camera.json for files when camera is a channel (videos always; vork help camera-json).PNG channels: depth and object_index grayscale16 (depth metres per unit in meta.jsonframes[].depth_unit_m); view_normal RGB8 = (v+1)/2; motion RGB16, RG = 0.5+0.5*offset in imageextents, clamped to ±1; shadow_catcher RGB16 linear, clamped 0..1; aov linear 16-bit, clamped 0..1.@@ -15,7 +15,7 @@ EXR channels: R,G,B,A; Z (metres, background 1e10); view_normal.X/Y/Z; object_inshadow_catcher.R/G/B (unclamped multiplicative light ratio); motion.X/Y (pixels, +Y down, current minus previous); aov <name>.X or <name>.R/G/B; float32.depth: view-axis metres to the nearest surface, not blended across edges.--exr-codec none|rle|zips|zip|piz|pxr24|b44|b44a|dwaa|dwab (default zip; pxr24/dwa are lossy).---diagnostics also writes NAME.timings.json.+--diagnostics: OUT/timings.json for directories; OUT.timings.json for files.shadow_catcher follows Cycles: catcher material light with CG / without CG, includingshadows, bounce and reflections. A zero baseline component is neutral 1 withoutdiff --git a/docs/help/profiles.md b/docs/help/profiles.mdindex 4af80ee..c73af0b 100644--- a/docs/help/profiles.md+++ b/docs/help/profiles.md@@ -6,7 +6,7 @@ highlights can narrow or change brightness; ray-camera effects can remain grainyJudge the finished lighting with final or path.std/draft: 4 samples with scene-ray indirect lighting and OIDN denoising.std/final: 8 samples, the default; scene-ray lighting and OIDN denoising.-std/path: accuracy, especially interiors, indirect lighting, glass and caustics.+std/path: 4096 samples; accuracy, especially interiors, indirect lighting, glass and caustics.Draft, final and path denoise with bundled OIDN by default. --set denoise=false uses the profilereconstruction (raw path samples for path); --set seed=42 makes sampling repeatable on the same backend.--set samples=N overrides the profile budget (1..4096); more samples means cleaner and slower.diff --git a/docs/help/programs.md b/docs/help/programs.mdindex 044a3ef..3daa4dd 100644--- a/docs/help/programs.md+++ b/docs/help/programs.md@@ -6,7 +6,7 @@ Procedural textures: import std.procedurals; signatures: vork help std --all.<!-- all -->PROGRAM REFERENCESlang modules: `import vork;`, one `struct Inputs {...}` whose initializers are-defaults, and any of these stages:+defaults; meshes require surface (lit/displace supplement surface):Closure|Blend|Hair surface(ShadingContext, Inputs)OpenPBR emission is shared by hits and light samples; lit output is authored shading.Light samples use zero differentials; hits retain their shading footprint.@@ -21,6 +21,8 @@ defaults, and any of these stages:float3 sensor(SensorContext, Inputs) per arriving contributionfloat3 display(DisplayContext, Inputs)void compute(ComputeContext, Inputs) buffers: <binding>_load/_store/_count; dense grids also <binding>_dims (uint3)+Initialized read-only global tables (including static const arrays) are allowed.+Global resources and mutable globals are refused; use Inputs or compute buffers.Inputs bind numbers, bools and enum tokens directly; Image {"image"}, Aov {"aov"},FloatGrid/VectorGrid {"grid"}, Attribute<float..float4> {"attribute"}.[InputRange(min, max, min_closed, max_closed)] on numeric Inputs fields validates@@ -37,7 +39,8 @@ DisplacementContext has only undisplaced object-local POSITION, NORMAL and timePer-instance displacement values use bound Attribute<T> inputs.For topology:"points", displace evaluates once per undisplaced object-local point centre and translates the whole sphere without changing its width; NORMAL and generated surface UV/tangent inputs are unavailable.-Procedural textures (wood, marble, stone, noise): import std.procedurals;+Noise primitives: import std.procedurals; compose noise/ramps for wood, marble or stone.+Wave and brick patterns: import blender.procedurals; vork help blender --all.signatures, case-sensitive enums and a surface example: vork help std --all.SIMULATIONdiff --git a/docs/help/sdk.md b/docs/help/sdk.mdindex d7e1691..26903b7 100644--- a/docs/help/sdk.md+++ b/docs/help/sdk.md@@ -1,10 +1,17 @@SDK+Start with vork init my-shot --language typescript (or --language python).+scene.json renders immediately; scene.ts/scene.py regenerates it with the matching SDK.Scenes are plain Python dicts or TypeScript objects with the JSON fields.Python: from vork import std, write_scene, render; install from PREFIX/lib/vork/python.-TypeScript: @usevoyager/vork; import builders, writeScene and render.+TypeScript: @voyager-so/vork; import builders, writeScene and render.Python std("sphere", name="ball", radius=0.5); TS sphere("ball", {radius:0.5}).Builders return buffers and geometry maps to merge into the scene.write_scene(scene, path, base_dir) / writeScene(scene, path, baseDir) rebase pathsand externalize large buffers. Keep the JSON with its referenced files.-render(scene_path, out, at=0) / render(path, {out, at:0}) return exposure summaries.-VORK_BIN selects the executable. Types: vork.types, TS Scene; schema: sdk/scene.schema.json.+render(scene_path, out, at=0) / render(path, {out, at:0}) return exposure summaries and warnings [{code,requested,dropped}] for omitted effects.+VORK_BIN selects the executable. Types: vork.types, TS Scene; schema: sdk/scene.schema.json in the archive (packages/ts/scene.schema.json in source).++The 0.2 SDK can render 0.1-compatible scenes with a 0.1 binary; absent warning+metadata returns an empty warnings list, not proof that all effects were rendered.+Writers preserve an explicit $schema but do not insert one. Omit $schema for 0.1.+New 0.2 commands/features still need a 0.2 binary. See vork help upgrade.diff --git a/docs/help/upgrade.md b/docs/help/upgrade.mdnew file mode 100644index 0000000..7f0ad1d--- /dev/null+++ b/docs/help/upgrade.md@@ -0,0 +1,98 @@+UPGRADE+Breaking changes, newest release first. Rewrite scenes/scripts; no aliases.++0.2 (from 0.1)+Before installing+- Keep your 0.1 binary/SDK and source scenes. Installing into the same PREFIX+ replaces 0.1; use a separate PREFIX to keep both, and set VORK_BIN explicitly+ when using SDKs. Keep each binary with its bundled runtime libraries.+- If scripts regenerate scatter, run them once with 0.1 BEFORE upgrading and+ save the written instance columns and all referenced buffers. 0.2 cannot run+ scatter builders; a seed alone cannot reconstruct 0.1 placements.++Scene and script changes+- Scatter builders: find scatter calls/imports or {"std":"scatter",...}.+ Replace with author-generated instance columns on the mesh, e.g.+ "instances":{"attributes":{"TRANSLATION":{"type":"vec3","data":[[0,0,0],[2,0,0]]}}}.+ Keep saved instance buffers for exact old placement; otherwise author the+ intended seeded distribution (a seed alone cannot recover old positions).+ Add equal-length ROTATION (XYZW) and SCALE buffers if used; retain custom+ columns and material bindings. See vork help field node.instances or vork help nodes --all.+- Render argument helpers: find TS renderArguments / Python render_arguments.+ Replace subprocess calls with TS render("shot.json", {out:"shot.png"}) or+ Python render("shot.json", "shot.png"). Import render from the same package.+ If managing the process yourself, write explicit arguments instead:+ ["render","shot.json","--out","shot.png","--set","samples=16"].+ Keep existing render options; see vork help render and vork help sdk.+- Removed compositor programs: find program values post/vignette,+ post/lens_distortion, post/glare in materials/render.compositor.+ Replace each with a local Slang composite program, e.g.+ {"program":"post/vignette","inputs":{"factor":0.5}} becomes+ {"program":{"file":"vignette.slang"},"inputs":{"factor":0.5}}.+ Copy the entire shipped examples/compositor-effects directory into your+ project (installed at PREFIX/lib/vork/examples/compositor-effects). It contains+ vignette.slang, chromatic-dispersion.slang, glare.slang and highlight.slang,+ plus complete glare-*.json merge graphs. Keep highlight.slang beside glare.slang;+ glare imports it. Program paths are relative to the scene; preserve inputs.+ The old lens effect was RGB chromatic dispersion, not geometric distortion.+ Glare produces an additive image: retain the original and merge it afterward,+ as examples/compositor-effects/glare-streaks.json demonstrates. std/bloom is+ still supported for bloom; it is not an exact replacement for these effects.+- Custom Slang imports also break: post.vignette, post.lens_distortion,+ post.glare and std.highlight were removed. Copy the same example modules next+ to your custom program. Use import vignette;, import glare; and import highlight;.+ For post.lens_distortion, copy chromatic-dispersion.slang as lens_distortion.slang+ and use import lens_distortion;. Update any qualified module references too.+- Fog/volume materials: std/fog, blender/principled_volume and blender.volume+ are no longer release programs. 0.1 could ignore legacy medium bindings with+ a warning; 0.2 fails with unknown-program errors. Remove unused definitions+ too. For a scene that relied on ignored fog, remove the medium-only nodes and+ their material bindings/definitions to retain the no-fog result. Preserve any+ surface material on shared geometry. There is no supported volumetric+ replacement in 0.2; keep 0.1 separately if you need its experimental behavior.+- Omitted mesh material: find meshes with omitted or empty materials. Default OpenPBR+ specular_roughness is now 0.3 instead of 0.5. To keep the old look, add+ "materials":[{"program":"std/openpbr","inputs":{"specular_roughness":0.5}}].+ Explicit and imported materials keep their own values.+- TS sky/environment options: find snake_case keys in sky(...) and+ environmentImage(...). Rename color_space -> colorSpace;+ sun_elevation -> sunElevation, sun_rotation -> sunRotation,+ air_density -> airDensity, aerosol_density -> aerosolDensity,+ ozone_density -> ozoneDensity, sun_size -> sunSize,+ sun_intensity -> sunIntensity. E.g. sky({sun_elevation:0.4}) becomes+ sky({sunElevation:0.4}). Python and scene JSON stay snake_case.+- TS package: replace @usevoyager/vork in imports and package manifests with+ @voyager-so/vork. Install the SDK from the native archive's sdk directory;+ this guide does not imply a registry release. See vork help sdk.++SDK/binary versions and rollback+- The 0.2 TS/Python render helpers accept 0.1 metadata without warnings and return+ warnings: []. That does not mean 0.1 rendered every requested effect. Select+ the intended executable with VORK_BIN; new commands such as init need 0.2.+- writeScene/write_scene no longer insert $schema; explicit $schema is preserved.+ 0.1 rejects this editor-only root field: remove it from scenes before rollback,+ including scenes made with vork init. Keep 0.1 source scenes and SDKs when+ rollback matters; 0.2-only features are not translated to 0.1 automatically.++Visible changes (recheck representative frames)+- Default std/final and std/draft denoising now filters in display-exposure units.+ Dim and high-exposure scenes can change substantially; recheck exposure and+ low-sample spectral detail. Undenoised reconstruction also changed, including+ denoise=false and the fallback on machines without GPU OIDN.+- Supplied mesh normals opposing triangle winding are aligned before shading;+ zero/degenerate normals use the face normal. Previously black metals can light+ correctly, and imported or hand-authored meshes can shade differently.+- std/path no longer counts finite-source lighting again at matched null-solid+ boundaries. One/two such slabs could previously produce 3x/5x overcounts.+ This correction changes path brightness; it does not change std/final.++Automation and performance+- Render stdout includes a Sidecars: line; setup starts with the vork version,+ OS: and FFmpeg version: lines. Progress goes to stderr every five seconds;+ the old "Shader cache is cold..." hint is gone. Do not parse by line position+ or treat any stderr as failure: check exit status, and use metadata sidecars+ or SDK results for exposure/warnings.+- Release-gate measurements found long interior/night std/final movies about+ 4.3-4.4% slower, smaller cached edits slower, and first video about 2 s slower.+ Three cold corpus preparations exceeded the 150 s deadline. These are measured+ workloads, not universal costs; allow headroom in automation timeouts.diff --git a/examples/compositor-effects/README.md b/examples/compositor-effects/README.mdnew file mode 100644index 0000000..a046c7d--- /dev/null+++ b/examples/compositor-effects/README.md@@ -0,0 +1,29 @@+# Authored compositor looks++Copy this entire directory from `PREFIX/lib/vork/examples/compositor-effects/`+(or `examples/compositor-effects/` in the archive or source checkout) to your+project. Keep `highlight.slang` beside `glare.slang`: glare imports it.++Use a local program reference in a compositor material:++```json+{"program":{"file":"vignette.slang"},"inputs":{"factor":0.5}}+```++Program paths are relative to the scene. Preserve the old material inputs.+`chromatic-dispersion.slang` replaces `post/lens_distortion`: it remaps RGB+channels independently, not geometric distortion. `glare-*.json` are complete,+self-contained scenes showing how to save the original image, run additive glare,+and merge it with the original. Run, for example:++```sh+vork render glare-streaks.json --out glare.png --at 0+```++For custom Slang imports, copy the required modules next to your program and+replace `post.vignette` with `vignette`, `post.glare` with `glare`,+`std.highlight` with `highlight`. For `post.lens_distortion`, copy+`chromatic-dispersion.slang` as `lens_distortion.slang` and use+`import lens_distortion;`. Update qualified module references too.+For shipped bloom, `vork help std/bloom` shows a two-entry graph; bloom is not+an exact replacement for these looks.diff --git a/libraries/post/lens_distortion.slang b/examples/compositor-effects/chromatic-dispersion.slangsimilarity index 91%rename from libraries/post/lens_distortion.slangrename to examples/compositor-effects/chromatic-dispersion.slangindex 6934a43..d72af5c 100644--- a/libraries/post/lens_distortion.slang+++ b/examples/compositor-effects/chromatic-dispersion.slang@@ -1,4 +1,4 @@-// Lens Distortion's dispersion only. The green channel remains at the camera UV.+// Chromatic dispersion. The green channel remains at the camera UV.import vork;public struct Inputs { [InputRange(0.0, 1.0, true, true)] float dispersion = 0.; };public float4 composite(CompositeContext ctx, Inputs inputs) { float2 uv=ctx.uv; float2 size=ctx.size; float time=ctx.time;diff --git a/examples/compositor-effects/glare-fog-glow.json b/examples/compositor-effects/glare-fog-glow.jsonnew file mode 100644index 0000000..cc4594d--- /dev/null+++ b/examples/compositor-effects/glare-fog-glow.json@@ -0,0 +1,180 @@+{+ "version": 2,+ "render": {+ "resolution": [+ 384,+ 216+ ],+ "fps": 12,+ "duration": 0.5,+ "background": [+ 0,+ 0,+ 0+ ],+ "compositor": [+ {"name":"glare0.original","material":{"program":{"source":"import vork; struct Inputs { Image source; }; float4 composite(CompositeContext c, Inputs i) { return compositor_load(i.source,int2(c.uv*c.size)); }"},"inputs":{"source":{"channel":"color"}}}},+ "effect",+ {"material":{"program":{"source":"import vork; struct Inputs { Image original; }; float4 composite(CompositeContext c, Inputs i) { return compositor_sample(i.original,c.uv)+compositor_sample(c.uv); }"},"inputs":{"original":{"node":"glare0.original"}}}},+ {"program":"post/white_balance","inputs":{"temperature":6500,"tint":10}}+ ]+ },+ "nodes": [+ {"type":"camera","name":"camera","translation":[0,0,5],"material":{"program":"std/camera","inputs":{"lens":50,"projection":"persp"}}},+ {+ "type": "mesh",+ "name": "amber",+ "geometry": "panel",+ "materials": [+ "amber"+ ],+ "translation": [-0.9,0,0]+ },+ {+ "type": "mesh",+ "name": "white",+ "geometry": "panel",+ "materials": [+ "white"+ ],+ "translation": [0.0,0,0]+ },+ {+ "type": "mesh",+ "name": "blue",+ "geometry": "panel",+ "materials": [+ "blue"+ ],+ "translation": [0.9,0,0]+ }+ ],+ "buffers": {+ "position": {+ "type": "vec3",+ "data": [+ [+ -0.16,+ -0.16,+ 0+ ],+ [+ 0.16,+ -0.16,+ 0+ ],+ [+ 0.16,+ 0.16,+ 0+ ],+ [+ -0.16,+ 0.16,+ 0+ ]+ ]+ },+ "normal": {+ "type": "vec3",+ "data": [+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ]+ ]+ },+ "index": {+ "type": "u32",+ "data": [+ 0,+ 1,+ 2,+ 0,+ 2,+ 3+ ]+ }+ },+ "geometry": {+ "panel": {+ "attributes": {+ "POSITION": "position",+ "NORMAL": "normal"+ },+ "indices": "index"+ }+ },+ "materials": {+ "amber": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 1,+ 0.25,+ 0.03+ ]+ }+ },+ "white": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 1,+ 1,+ 1+ ]+ }+ },+ "blue": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 0.03,+ 0.2,+ 1+ ]+ }+ },+ "effect": {+ "program":{"file":"glare.slang"},+ "inputs": {+ "type": "fog_glow",+ "strength": 2.0+ }+ }+ },+ "animation": [+ {+ "tracks": [+ {+ "path": [+ "nodes",+ "white",+ "translation"+ ],+ "keys": [[0,[0,-0.3,0]],[0.5,[0,0.3,0]]]+ }+ ]+ }+ ]+}diff --git a/examples/compositor-effects/glare-fog-glow.profile.json b/examples/compositor-effects/glare-fog-glow.profile.jsonnew file mode 100644index 0000000..9b42462--- /dev/null+++ b/examples/compositor-effects/glare-fog-glow.profile.json@@ -0,0 +1,9 @@+{+ "version": 1,+ "level": 0,+ "settings": {+ "seed": 0,+ "denoise": false+ },+ "description": "Compositor preview without denoising."+}diff --git a/examples/compositor-effects/glare-ghosts.json b/examples/compositor-effects/glare-ghosts.jsonnew file mode 100644index 0000000..68248a8--- /dev/null+++ b/examples/compositor-effects/glare-ghosts.json@@ -0,0 +1,180 @@+{+ "version": 2,+ "render": {+ "resolution": [+ 384,+ 216+ ],+ "fps": 12,+ "duration": 0.5,+ "background": [+ 0,+ 0,+ 0+ ],+ "compositor": [+ {"name":"glare0.original","material":{"program":{"source":"import vork; struct Inputs { Image source; }; float4 composite(CompositeContext c, Inputs i) { return compositor_load(i.source,int2(c.uv*c.size)); }"},"inputs":{"source":{"channel":"color"}}}},+ "effect",+ {"material":{"program":{"source":"import vork; struct Inputs { Image original; }; float4 composite(CompositeContext c, Inputs i) { return compositor_sample(i.original,c.uv)+compositor_sample(c.uv); }"},"inputs":{"original":{"node":"glare0.original"}}}},+ {"program":"post/white_balance","inputs":{"temperature":6500,"tint":10}}+ ]+ },+ "nodes": [+ {"type":"camera","name":"camera","translation":[0,0,5],"material":{"program":"std/camera","inputs":{"lens":50,"projection":"persp"}}},+ {+ "type": "mesh",+ "name": "amber",+ "geometry": "panel",+ "materials": [+ "amber"+ ],+ "translation": [-0.9,0,0]+ },+ {+ "type": "mesh",+ "name": "white",+ "geometry": "panel",+ "materials": [+ "white"+ ],+ "translation": [0.0,0,0]+ },+ {+ "type": "mesh",+ "name": "blue",+ "geometry": "panel",+ "materials": [+ "blue"+ ],+ "translation": [0.9,0,0]+ }+ ],+ "buffers": {+ "position": {+ "type": "vec3",+ "data": [+ [+ -0.16,+ -0.16,+ 0+ ],+ [+ 0.16,+ -0.16,+ 0+ ],+ [+ 0.16,+ 0.16,+ 0+ ],+ [+ -0.16,+ 0.16,+ 0+ ]+ ]+ },+ "normal": {+ "type": "vec3",+ "data": [+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ]+ ]+ },+ "index": {+ "type": "u32",+ "data": [+ 0,+ 1,+ 2,+ 0,+ 2,+ 3+ ]+ }+ },+ "geometry": {+ "panel": {+ "attributes": {+ "POSITION": "position",+ "NORMAL": "normal"+ },+ "indices": "index"+ }+ },+ "materials": {+ "amber": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 1,+ 0.25,+ 0.03+ ]+ }+ },+ "white": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 1,+ 1,+ 1+ ]+ }+ },+ "blue": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 0.03,+ 0.2,+ 1+ ]+ }+ },+ "effect": {+ "program":{"file":"glare.slang"},+ "inputs": {+ "type": "ghosts",+ "strength": 2.0+ }+ }+ },+ "animation": [+ {+ "tracks": [+ {+ "path": [+ "nodes",+ "white",+ "translation"+ ],+ "keys": [[0,[0,-0.3,0]],[0.5,[0,0.3,0]]]+ }+ ]+ }+ ]+}diff --git a/examples/compositor-effects/glare-ghosts.profile.json b/examples/compositor-effects/glare-ghosts.profile.jsonnew file mode 100644index 0000000..9b42462--- /dev/null+++ b/examples/compositor-effects/glare-ghosts.profile.json@@ -0,0 +1,9 @@+{+ "version": 1,+ "level": 0,+ "settings": {+ "seed": 0,+ "denoise": false+ },+ "description": "Compositor preview without denoising."+}diff --git a/examples/compositor-effects/glare-simple-star.json b/examples/compositor-effects/glare-simple-star.jsonnew file mode 100644index 0000000..f00a1ad--- /dev/null+++ b/examples/compositor-effects/glare-simple-star.json@@ -0,0 +1,180 @@+{+ "version": 2,+ "render": {+ "resolution": [+ 384,+ 216+ ],+ "fps": 12,+ "duration": 0.5,+ "background": [+ 0,+ 0,+ 0+ ],+ "compositor": [+ {"name":"glare0.original","material":{"program":{"source":"import vork; struct Inputs { Image source; }; float4 composite(CompositeContext c, Inputs i) { return compositor_load(i.source,int2(c.uv*c.size)); }"},"inputs":{"source":{"channel":"color"}}}},+ "effect",+ {"material":{"program":{"source":"import vork; struct Inputs { Image original; }; float4 composite(CompositeContext c, Inputs i) { return compositor_sample(i.original,c.uv)+compositor_sample(c.uv); }"},"inputs":{"original":{"node":"glare0.original"}}}},+ {"program":"post/white_balance","inputs":{"temperature":6500,"tint":10}}+ ]+ },+ "nodes": [+ {"type":"camera","name":"camera","translation":[0,0,5],"material":{"program":"std/camera","inputs":{"lens":50,"projection":"persp"}}},+ {+ "type": "mesh",+ "name": "amber",+ "geometry": "panel",+ "materials": [+ "amber"+ ],+ "translation": [-0.9,0,0]+ },+ {+ "type": "mesh",+ "name": "white",+ "geometry": "panel",+ "materials": [+ "white"+ ],+ "translation": [0.0,0,0]+ },+ {+ "type": "mesh",+ "name": "blue",+ "geometry": "panel",+ "materials": [+ "blue"+ ],+ "translation": [0.9,0,0]+ }+ ],+ "buffers": {+ "position": {+ "type": "vec3",+ "data": [+ [+ -0.16,+ -0.16,+ 0+ ],+ [+ 0.16,+ -0.16,+ 0+ ],+ [+ 0.16,+ 0.16,+ 0+ ],+ [+ -0.16,+ 0.16,+ 0+ ]+ ]+ },+ "normal": {+ "type": "vec3",+ "data": [+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ]+ ]+ },+ "index": {+ "type": "u32",+ "data": [+ 0,+ 1,+ 2,+ 0,+ 2,+ 3+ ]+ }+ },+ "geometry": {+ "panel": {+ "attributes": {+ "POSITION": "position",+ "NORMAL": "normal"+ },+ "indices": "index"+ }+ },+ "materials": {+ "amber": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 1,+ 0.25,+ 0.03+ ]+ }+ },+ "white": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 1,+ 1,+ 1+ ]+ }+ },+ "blue": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 0.03,+ 0.2,+ 1+ ]+ }+ },+ "effect": {+ "program":{"file":"glare.slang"},+ "inputs": {+ "type": "simple_star",+ "strength": 2.0+ }+ }+ },+ "animation": [+ {+ "tracks": [+ {+ "path": [+ "nodes",+ "white",+ "translation"+ ],+ "keys": [[0,[0,-0.3,0]],[0.5,[0,0.3,0]]]+ }+ ]+ }+ ]+}diff --git a/examples/compositor-effects/glare-simple-star.profile.json b/examples/compositor-effects/glare-simple-star.profile.jsonnew file mode 100644index 0000000..9b42462--- /dev/null+++ b/examples/compositor-effects/glare-simple-star.profile.json@@ -0,0 +1,9 @@+{+ "version": 1,+ "level": 0,+ "settings": {+ "seed": 0,+ "denoise": false+ },+ "description": "Compositor preview without denoising."+}diff --git a/examples/compositor-effects/glare-streaks.json b/examples/compositor-effects/glare-streaks.jsonnew file mode 100644index 0000000..67298cc--- /dev/null+++ b/examples/compositor-effects/glare-streaks.json@@ -0,0 +1,180 @@+{+ "version": 2,+ "render": {+ "resolution": [+ 384,+ 216+ ],+ "fps": 12,+ "duration": 0.5,+ "background": [+ 0,+ 0,+ 0+ ],+ "compositor": [+ {"name":"glare0.original","material":{"program":{"source":"import vork; struct Inputs { Image source; }; float4 composite(CompositeContext c, Inputs i) { return compositor_load(i.source,int2(c.uv*c.size)); }"},"inputs":{"source":{"channel":"color"}}}},+ "effect",+ {"material":{"program":{"source":"import vork; struct Inputs { Image original; }; float4 composite(CompositeContext c, Inputs i) { return compositor_sample(i.original,c.uv)+compositor_sample(c.uv); }"},"inputs":{"original":{"node":"glare0.original"}}}},+ {"program":"post/white_balance","inputs":{"temperature":6500,"tint":10}}+ ]+ },+ "nodes": [+ {"type":"camera","name":"camera","translation":[0,0,5],"material":{"program":"std/camera","inputs":{"lens":50,"projection":"persp"}}},+ {+ "type": "mesh",+ "name": "amber",+ "geometry": "panel",+ "materials": [+ "amber"+ ],+ "translation": [-0.9,0,0]+ },+ {+ "type": "mesh",+ "name": "white",+ "geometry": "panel",+ "materials": [+ "white"+ ],+ "translation": [0.0,0,0]+ },+ {+ "type": "mesh",+ "name": "blue",+ "geometry": "panel",+ "materials": [+ "blue"+ ],+ "translation": [0.9,0,0]+ }+ ],+ "buffers": {+ "position": {+ "type": "vec3",+ "data": [+ [+ -0.16,+ -0.16,+ 0+ ],+ [+ 0.16,+ -0.16,+ 0+ ],+ [+ 0.16,+ 0.16,+ 0+ ],+ [+ -0.16,+ 0.16,+ 0+ ]+ ]+ },+ "normal": {+ "type": "vec3",+ "data": [+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ],+ [+ 0,+ 0,+ 1+ ]+ ]+ },+ "index": {+ "type": "u32",+ "data": [+ 0,+ 1,+ 2,+ 0,+ 2,+ 3+ ]+ }+ },+ "geometry": {+ "panel": {+ "attributes": {+ "POSITION": "position",+ "NORMAL": "normal"+ },+ "indices": "index"+ }+ },+ "materials": {+ "amber": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 1,+ 0.25,+ 0.03+ ]+ }+ },+ "white": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 1,+ 1,+ 1+ ]+ }+ },+ "blue": {+ "inputs": {+ "base_weight": 0,+ "emission_luminance": 100,+ "emission_color": [+ 0.03,+ 0.2,+ 1+ ]+ }+ },+ "effect": {+ "program":{"file":"glare.slang"},+ "inputs": {+ "type": "streaks",+ "strength": 2.0+ }+ }+ },+ "animation": [+ {+ "tracks": [+ {+ "path": [+ "nodes",+ "white",+ "translation"+ ],+ "keys": [[0,[0,-0.3,0]],[0.5,[0,0.3,0]]]+ }+ ]+ }+ ]+}diff --git a/examples/compositor-effects/glare-streaks.profile.json b/examples/compositor-effects/glare-streaks.profile.jsonnew file mode 100644index 0000000..9b42462--- /dev/null+++ b/examples/compositor-effects/glare-streaks.profile.json@@ -0,0 +1,9 @@+{+ "version": 1,+ "level": 0,+ "settings": {+ "seed": 0,+ "denoise": false+ },+ "description": "Compositor preview without denoising."+}diff --git a/libraries/post/glare.slang b/examples/compositor-effects/glare.slangsimilarity index 99%rename from libraries/post/glare.slangrename to examples/compositor-effects/glare.slangindex 13798aa..f8fa937 100644--- a/libraries/post/glare.slang+++ b/examples/compositor-effects/glare.slang@@ -23,7 +23,7 @@ public struct Inputs {};static const float GLARE_PI = 3.141592653589793;static const int GLARE_LINE_TAPS = 128;-import std.highlight;+import highlight;float3 glare_spectral(float3 c,float phase,float modulation) {float3 weights=0.5+0.5*cos(phase+float3(0.,2.*GLARE_PI/3.,4.*GLARE_PI/3.));return c*lerp(float3(1),weights*2.,saturate(modulation));diff --git a/libraries/std/highlight.slang b/examples/compositor-effects/highlight.slangsimilarity index 100%rename from libraries/std/highlight.slangrename to examples/compositor-effects/highlight.slangdiff --git a/libraries/post/vignette.slang b/examples/compositor-effects/vignette.slangsimilarity index 100%rename from libraries/post/vignette.slangrename to examples/compositor-effects/vignette.slangdiff --git a/install.ps1 b/install.ps1index 00d3ac9..859db87 100644--- a/install.ps1+++ b/install.ps1@@ -10,7 +10,7 @@ $ErrorActionPreference = 'Stop'$ProgressPreference = 'SilentlyContinue'$repo = if ($env:VORK_REPO) { $env:VORK_REPO } else { 'voyager-so/vork' }# Default version is generated from Cargo.toml by scripts/sync-version.-$version = if ($env:VERSION) { $env:VERSION } else { '0.1.0' }+$version = if ($env:VERSION) { $env:VERSION } else { '0.2.0' }$prefix = if ($env:PREFIX) { $env:PREFIX } else { Join-Path $env:LOCALAPPDATA 'Programs\vork' }if ($version -notmatch '^[A-Za-z0-9._-]+$') { throw 'Invalid VERSION' }$arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }diff --git a/install.sh b/install.shindex b0655af..46a9d67 100755--- a/install.sh+++ b/install.sh@@ -5,7 +5,7 @@set -eurepo=${VORK_REPO:-voyager-so/vork}# Default version is generated from Cargo.toml by scripts/sync-version.-version=${VERSION:-0.1.0}+version=${VERSION:-0.2.0}default_prefix=$HOME/.localprefix=${PREFIX:-"$default_prefix"}dry_run=false@@ -30,8 +30,13 @@ esacarchive="vork-${version}-${platform}.tar.gz"base=${VORK_DOWNLOAD_BASE:-"https://github.com/$repo/releases/download/v$version"}base=${base%/}+# A downloaded installer can accompany an archive; piped installs still download.+installer_dir=+if [ -f "$0" ]; then installer_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P); fiif "$dry_run"; then- printf 'Archive: %s/%s\nChecksums: %s/SHA256SUMS\nBinary: %s/bin/vork\n' "$base" "$archive" "$base" "$prefix"+ source_base=$base+ if [ -n "$installer_dir" ] && [ -f "$installer_dir/$archive" ]; then source_base=$installer_dir; fi+ printf 'Archive: %s/%s\nChecksums: %s/SHA256SUMS\nBinary: %s/bin/vork\n' "$source_base" "$archive" "$source_base" "$prefix"exit 0ficommand -v curl >/dev/null 2>&1 || { echo 'vork install needs curl; install it and run this again.' >&2; exit 1; }@@ -52,8 +57,15 @@ fetch() {exit 1}}-fetch "$archive"-fetch SHA256SUMS+if [ -n "$installer_dir" ] && [ -f "$installer_dir/$archive" ]; then+ echo "Using bundled archive: $installer_dir/$archive"+ [ -f "$installer_dir/SHA256SUMS" ] || { echo 'Bundled archive requires SHA256SUMS beside install.sh' >&2; exit 1; }+ cp "$installer_dir/$archive" "$work/$archive"+ cp "$installer_dir/SHA256SUMS" "$work/SHA256SUMS"+else+ fetch "$archive"+ fetch SHA256SUMS+fi(cd "$work" || exit 1awk -v name="$archive" '$2 == name || $2 == "*" name {print}' SHA256SUMS > selected.sha256diff --git a/libraries/post/HELP.txt b/libraries/post/HELP.txtindex d80de46..dce97c4 100644--- a/libraries/post/HELP.txt+++ b/libraries/post/HELP.txt@@ -1,12 +1,9 @@-post: optional compositor looks: post/glare (streaks, ghosts, fog_glow, simple_star),-post/vignette, post/lens_distortion, post/white_balance. Inputs: post --all.+post: white balance colour adaptation. Inputs: post --all.<!-- all -->-Program: "program":"post/<module>" in render.compositor Slang import: import post.<module>;-Bloom is std/bloom.+Program: "program":"post/white_balance" in render.compositor.+post/white_balance: source white to D65; temperature 6500 K (1800..100000), tint 10 (-500..500); preserves alpha, affects linear outputs.+Authored glare, vignette and chromatic dispersion: examples/compositor-effects/.-PROGRAMS-post/glare: Blender Glare node looks: type streaks|ghosts|fog_glow|simple_star; threshold, smoothness, clamp, maximum, strength, saturation, tint, size, streaks, streaks_angle, iterations, fade, color_modulation, diagonal, quality high|medium|low-post/vignette: darkens edges: position, size, rotation, blur_size, factor-post/lens_distortion: Lens Distortion dispersion only: dispersion [0,1]--post/white_balance: source white to D65; temperature 6500 K (1800..100000), tint 10 (-500..500); preserves alpha, affects linear outputs+Copy the entire examples/compositor-effects directory; glare needs highlight.slang+next to it. The shipped glare-streaks.json demonstrates the additive merge graph.+See vork help upgrade for 0.1 program and Slang-import replacements.diff --git a/libraries/std/HELP.txt b/libraries/std/HELP.txtindex dd51060..19dee7e 100644--- a/libraries/std/HELP.txt+++ b/libraries/std/HELP.txt@@ -13,8 +13,7 @@ SDK builders default the name likewise; pass undefined before required options.round shapes use Y as axis. Cylinder has both caps; cone has a bottom cap; size = full extent; capsule height includescaps; torus radius is to the tube centre. Radii and bevels clamp to fit without overlap, scaling unequal corners together; extrusion rims fit depth/2 and profile clearance. Negative or non-finite values are errors. Rounded box segments subdivide the bevel(rounded up to an even count), preserving exact planar faces at every count. Box faces each span 0..1 UV; round shapes: u from +X toward--Z around Y, v top to bottom. scatter returns InstanceFragment: merge its buffers into the scene and-set mesh.instances to its instances; local +Y follows the face normal.+-Z around Y, v top to bottom.<!-- generated-shapes:start -->cylinder: {name?:string="cylinder",radius?:number=1,height?:number=2,segments?:number=32} → GeometryFragmentcone: {name?:string="cone",radius?:number=1,height?:number=2,segments?:number=32} → GeometryFragment@@ -22,7 +21,6 @@ torus: {name?:string="torus",radius?:number=1,tube?:number=0.25,segments?:numbercapsule: {name?:string="capsule",radius?:number=0.5,height?:number=2,segments?:number=32,rings?:number=24} → GeometryFragmentrounded_box: {name?:string="rounded_box",size?:vec3=[1,1,1],radius?:number=0.1,segments?:number=8} → GeometryFragmentrevolve: {name?:string="revolve",profile:vec2[],segments?:number=32} → GeometryFragment; profile:[radius,height][] around +Y; consecutive duplicates ignored; radius-0 ends close; other ends open; last=first closes loop; corners >30° sharp; u from +X toward -Z, v along profile-scatter: {on_geometry:{buffers:{ [k: string]: Buffer; },geometry:{ [k: string]: Geometry; }},count:number,seed:number,name?:string} → InstanceFragmenttext: {name?:string="text",body:string,font:string,size?:number,extrude?:number,bevel_depth?:number,bevel_resolution?:number,align_x?:"left"|"center"|"right"|"justify"|"flush",align_y?:"center"|"top_baseline"|"top"|"bottom_baseline"|"bottom"} → GeometryFragment; font:TrueType/OpenType file; extrude:half-depth; bevel_depth:metresextrude: {name?:string="extrude",outline:vec2[],holes?:vec2[][],depth?:number=1,bevel_depth?:number=0,bevel_resolution?:number=4} → GeometryFragment; XY outline/holes: either winding; depth:full Z thickness, centred; +Z front; bevel_depth:inward rim radius; bevel_resolution:1..32; wall corners >30° sharp; cap uv spans outline bounds (v down); wall u along contour, v front→back<!-- generated-shapes:end -->@@ -34,8 +32,8 @@ offset, random_roughness, random_color, random. Physical hair selects path transstd/environment_image: Image image; optional Image lighting_weight; lat-long +Y up, longitude atan2(z,x)/2pi+0.5; lighting_weight.r weights lighting only (unbound = 1).std/sky: Nishita scattering atmosphere; sun_elevation, sun_rotation, altitude, air_density, aerosol_density, ozone_density.vork std sky: atmosphere plus declared solar light; sun_size is full angle, sun_intensity scales solar emission.-vork std environment: {file,output,name?,threshold?,color_space?}; weight EXR plus environment program and declared sun; threshold defaults to 10.-std/bloom inputs: vork help compositor.+vork std environment: {file,output,name?,threshold?,color_space?,fps?}; weight EXR plus environment program and declared sun; threshold defaults to 10.+std/bloom: add prepare(original={channel:color}), named highlights, then combine(original={channel:color},source={node:highlights}) to render.compositor. stage is an input; adjust prepare threshold=1 and combine strength=1. Full JSON: vork help compositor.Modules (import std.<m>):std.texture: texture_footprint(uv,dx,dy,ctx); texture_sample(image,footprint,ctx).texture_normal(image,footprint,ctx,factors,derived,out variance) and texture_tangent(image,footprint,ctx,factors,derived) return world-space vectors.@@ -74,7 +72,6 @@ std.color: color_ramp<N>(factor, RampStop[N], constant|linear|ease|cardinal|b_spnear|far|cw|ccw); blackbody(kelvin); wavelength(nm)std.grid: sample_grid(FloatGrid|VectorGrid, position)std.hair_bsdf: principled_hair, hair_melanin, hair_absorption, hair_evaluate, hair_sample-scatter: merge returned buffers into Scene, set mesh.instances; local +Y follows the face normal.std.particles: Yu–Turk anisotropic particle-surface mathematics (ACM TOG 2013).particle_moment(inout ParticleMoments, relative:float3, neighbourhood_radius:float):diff --git a/packages/python/README.md b/packages/python/README.mdindex cacb27d..c1ac7f6 100644--- a/packages/python/README.md+++ b/packages/python/README.md@@ -40,7 +40,10 @@ Readers therefore see a matching pair, including during concurrent saves. Olderare retained for readers holding previous JSON snapshots; interrupted saves can also leaveunreferenced sidecars. Fresh files are private; replacement JSON preserves existing permissions.-`render()` prints the CLI exposure lines and returns `{exposure: [{output, exposure}]}`.+`render()` prints the CLI exposure lines and returns `{exposure: [{output, exposure}], warnings}`.+`warnings` contains `{code, requested, dropped}` records for requested effects+omitted or substituted by the renderer, also printed prominently by the CLI and+written into each render metadata sidecar. Check this array before accepting a render.Each summary contains `frames`, `coverage` (mean alpha), `clipped`, `near_black`, `mean`, and`worst_clipped`/`worst_near_black` (`share`, absolute `frame`). EXR and control-onlyoutputs have no entry. Statistics weight display RGB by alpha; empty coverage gives@@ -50,3 +53,10 @@ retain full precision from the output metadata.Surface programs author emitted light once with OpenPBR `emission_color` and`emission_luminance`; hits and light samples share that evaluation. Use `lit`for authored glow that should not become a sampled light.++Scene JSON may include `"$schema": "https://voyager.so/vork/schema/scene.schema.json"` for editor+completion and validation. This metadata does not affect rendering and is never+fetched by vork. `vork init` includes it automatically. SDK writers preserve an explicit `$schema`+but do not insert one, so 0.1-compatible scenes still load in 0.1. Remove an+explicit `$schema` before using a 0.1 binary. SDK render helpers accept 0.1+metadata without warnings and return an empty warnings list in that case.diff --git a/packages/python/pyproject.toml b/packages/python/pyproject.tomlindex 9113657..a6b9cab 100644--- a/packages/python/pyproject.toml+++ b/packages/python/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "vork"-version = "0.1.0"+version = "0.2.0"requires-python = ">=3.11"description = "Generated scene types and shared standard library for vork"license = "LicenseRef-vork-Preview"@@ -13,4 +13,4 @@ license = "LicenseRef-vork-Preview"packages = ["vork"][tool.setuptools.package-data]-vork = ["py.typed"]+vork = ["py.typed", "_resource_slots.json"]diff --git a/packages/python/test_options.py b/packages/python/test_options.pyindex 85aa8e1..4528587 100644--- a/packages/python/test_options.py+++ b/packages/python/test_options.py@@ -1,5 +1,5 @@import unittest-from vork import std, render, render_arguments+from vork import std, render, _render_arguments as render_argumentsfrom vork._validate import _check_optionsdiff --git a/packages/python/test_render.py b/packages/python/test_render.pyindex 6cb83dd..ee1e82a 100644--- a/packages/python/test_render.py+++ b/packages/python/test_render.py@@ -14,6 +14,7 @@ class RenderExposure(unittest.TestCase):empty = dict(frames=1, coverage=0, clipped=None, near_black=None, mean=None,worst_clipped=None, worst_near_black=None)summaries = [summary, empty, summary]+ warning = dict(code="additional_environment", requested={"node": {"name": "second", "energy": 2}}, dropped="second environment; retaining first")with tempfile.TemporaryDirectory() as directory:outputs = [os.path.join(directory, p) for p in ['still.png', 'clip.MOV', 'frames.png/', 'controls', 'exr/%06d.exr']]paths = ['still.png.meta.json', 'clip.MOV.meta.json', 'frames.png/meta.json', 'controls/meta.json', 'exr/meta.json']@@ -21,11 +22,21 @@ class RenderExposure(unittest.TestCase):path = os.path.join(directory, path)os.makedirs(os.path.dirname(path), exist_ok=True)with open(path, 'w') as f:- json.dump({'exposure': summaries[i]} if i < 3 else {}, f)+ json.dump({'exposure': summaries[i], 'warnings': [warning]} if i < 3 else {'warnings': [warning]}, f)with patch('subprocess.run') as run:result = render('shot.json', outputs)self.assertEqual(run.call_args.kwargs, {'check': True})- self.assertEqual(result, {'exposure': [{'output': out, 'exposure': summaries[i]} for i, out in enumerate(outputs[:3])]})+ self.assertEqual(result, {'exposure': [{'output': out, 'exposure': summaries[i]} for i, out in enumerate(outputs[:3])], 'warnings': [warning]})++ def test_01_metadata_without_warnings_preserves_exposure(self):+ summary = {'frames': 1, 'coverage': 1, 'mean': 0.4}+ with tempfile.TemporaryDirectory() as directory:+ output = os.path.join(directory, 'still.png')+ with open(output + '.meta.json', 'w') as f:+ json.dump({'exposure': summary}, f)+ with patch('subprocess.run'):+ self.assertEqual(render('shot.json', output), {+ 'exposure': [{'output': output, 'exposure': summary}], 'warnings': []})if __name__ == '__main__':diff --git a/packages/python/test_resource_slots.py b/packages/python/test_resource_slots.pynew file mode 100644index 0000000..f85af31--- /dev/null+++ b/packages/python/test_resource_slots.py@@ -0,0 +1,70 @@+"""Enumerate file slots independently from the full published schema, not the writer graph."""+import copy+import json+import os+from pathlib import Path+import tempfile+import unittest+from vork import write_scene++SCHEMA = json.loads((Path(__file__).parent.parent / 'ts/scene.schema.json').read_text())+++def resource_paths(node, seen=frozenset(), path=()):+ if not isinstance(node, dict):+ return+ if '$ref' in node:+ ref = node['$ref'].split('/')[-1]+ if ref not in seen:+ yield from resource_paths(SCHEMA['$defs'][ref], seen | {ref}, path)+ for key in ('anyOf', 'oneOf', 'allOf'):+ for child in node.get(key, []):+ yield from resource_paths(child, seen, path)+ for key, child in node.get('properties', {}).items():+ if key in ('file', 'source_origin') and 'string' in str(child.get('type')):+ yield path + (key,)+ else:+ yield from resource_paths(child, seen, path + (key,))+ if 'items' in node:+ yield from resource_paths(node['items'], seen, path + (0,))+ if isinstance(node.get('additionalProperties'), dict):+ # Opaque table/input names deliberately collide with a structural field.+ yield from resource_paths(node['additionalProperties'], seen, path + ('file',))+++def cases():+ paths = set(resource_paths(SCHEMA))+ paths |= {('nodes', 0, 'children', 0) + p[2:] for p in paths if p[:1] == ('nodes',)}+ paths |= {('images', 'nested', 'render') + p[1:] for p in paths if p[:2] == ('render', 'compositor')}+ return sorted(paths, key=str)+++def scene_at(path):+ value = 'resource.bin'+ for key in reversed(path):+ value = [value] if isinstance(key, int) else {key: value}+ return {'version': 2, 'nodes': [], **value}+++class ResourceSlots(unittest.TestCase):+ def test_all_schema_resource_slots_preserve_source_identity(self):+ with tempfile.TemporaryDirectory() as root:+ source = Path(root) / 'source'+ source.mkdir()+ ((source / 'resource.bin').resolve()).write_bytes(b'resource')+ for path in cases():+ with self.subTest(path=path):+ scene = scene_at(path)+ original = copy.deepcopy(scene)+ output = Path(write_scene(scene, str(Path(root) / 'export/scene.json'), str(source)))+ saved = json.loads(output.read_text())+ value = saved+ for key in path:+ value = value[key]+ self.assertEqual((output.parent / value).resolve(), (source / 'resource.bin').resolve())+ self.assertEqual(scene, original)+++if __name__ == '__main__':+ # TypeScript consumes the same exhaustive cases, while using its own writer.+ print(json.dumps([{'path': p, 'scene': scene_at(p)} for p in cases()]))diff --git a/packages/python/test_types.py b/packages/python/test_types.pyindex 3017874..e1be04e 100644--- a/packages/python/test_types.py+++ b/packages/python/test_types.py@@ -1,10 +1,14 @@import unittestfrom typing import get_args, get_type_hints, is_typeddict-from vork import std, render_arguments+from vork import std, _render_arguments as render_argumentsimport vork.types as typesclass GeneratedTypes(unittest.TestCase):+ def test_argv_builder_is_private(self):+ import vork+ self.assertFalse(hasattr(vork, "render_arguments"))+def test_all_references_resolve(self):for value in vars(types).values():if is_typeddict(value):diff --git a/packages/python/test_write.py b/packages/python/test_write.pyindex 6451ecb..b42e823 100644--- a/packages/python/test_write.py+++ b/packages/python/test_write.py@@ -24,6 +24,12 @@ class WriteScene(unittest.TestCase):}, 'animation': animation}with tempfile.TemporaryDirectory() as directory:saved = self.read(write_scene(scene, os.path.join(directory, 'scene.json')))+ self.assertNotIn('$schema', saved)+ self.assertNotIn('$schema', scene)+ annotated = dict(scene, **{'$schema': 'https://voyager.so/vork/schema/scene.schema.json'})+ annotated_path = write_scene(annotated, os.path.join(directory, 'annotated.json'), directory)+ with open(annotated_path) as f:+ self.assertEqual(json.load(f)['$schema'], annotated['$schema'])self.assertEqual(saved['animation'], animation)self.assertEqual(saved['materials'], scene['materials'])diff --git a/packages/python/vork/__init__.py b/packages/python/vork/__init__.pyindex 8fcf505..03c4ac4 100644--- a/packages/python/vork/__init__.py+++ b/packages/python/vork/__init__.py@@ -5,6 +5,7 @@ import hashlibimport jsonimport mathimport os+from ._engine import engine as _engineimport structimport statimport subprocess@@ -14,7 +15,7 @@ from typing import Any, Optional, Sequence, Union, TypedDictfrom .types import Scenefrom ._validate import helper_options as _helper_options-# SDK authoring choice shared with @usevoyager/vork: externalize buffers of at least 4 KiB.+# SDK authoring choice shared with @voyager-so/vork: externalize buffers of at least 4 KiB.BINARY_BUFFER_MIN_BYTES = 4096_WIDTHS = {'f32': 1, 'i32': 1, 'u32': 1, 'vec2': 2, 'vec3': 3, 'vec4': 4, 'uvec4': 4, 'mat4': 16}@@ -102,7 +103,7 @@ def _external_buffers(scene: dict, file: str) -> Optional[bytes]:def write_scene(scene: Scene, path: str, base_dir: Optional[str] = None) -> str:"""Write scene JSON with relative resource paths and a binary sidecar for large buffers.- Mirrors writeScene in @usevoyager/vork: resource paths resolve against base_dir (default:+ Mirrors writeScene in @voyager-so/vork: resource paths resolve against base_dir (default:the working directory) and are written relative to the scene's directory; inline buffersof at least 4 KiB go to an immutable PATH.buffers.UUID.bin sidecar. The JSON isatomically replaced after its sidecar is complete; old sidecars are retained for readers. The input is not@@ -126,82 +127,32 @@ def write_scene(scene: Scene, path: str, base_dir: Optional[str] = None) -> str:result = copy.deepcopy(scene)- # Resource slots mirror crates/vork-scene/src/v2/inline.rs. Walk definitions- # before their dependencies, never interpreting user-defined table/input names- # as fields (an input named "file" is not a filesystem path).- seen = set()-- def each(value):- return value.values() if isinstance(value, dict) else value or []-- def resource(kind, value):- if not isinstance(value, dict) or id(value) in seen:- return- seen.add(id(value))- for field in ('file', 'source_origin') if kind == 'programs' else ('file',) if kind in ('images', 'buffers') else ():- if isinstance(value.get(field), str):- value[field] = asset_path(value[field])- if kind == 'geometry':- for field in ('indices', 'curve_vertex_counts', 'widths'):- resource('buffers', value.get(field))- for buffer in each(value.get('attributes')):- resource('buffers', buffer)- for morph in each(value.get('morphs')):- for field in ('POSITION', 'NORMAL'):- resource('buffers', morph.get(field))- elif kind == 'materials':- resource('programs', value.get('program'))- for input in each(value.get('inputs')):- if isinstance(input, dict):- resource('images', input.get('image'))- resource('buffers', input.get('grid'))- elif kind == 'images':- render(value.get('render') or {})- elif kind == 'programs':- for buffer in each(value.get('bindings')):- resource('buffers', buffer)-- def render(value):- resource('materials', value.get('display'))- for field in ('compositor', 'compositor_per_step'):- for material in each(value.get(field)):- resource('materials', material)-- def visit(node):- if node.get('type') == 'asset':- node['file'] = asset_path(node['file'])- if node.get('type') in ('mesh', 'asset'):- resource('geometry', node.get('geometry'))- for material in each(node.get('materials')):- resource('materials', material)- if node.get('type') == 'mesh':- instances = node.get('instances') or {}- resource('buffers', instances.get('count'))- for buffer in each(instances.get('attributes')):- resource('buffers', buffer)- resource('buffers', (node.get('skin') or {}).get('inverse_bind_matrices'))- if node.get('type') == 'light':- resource('images', node.get('image'))- for field in ('material',):- resource('materials', node.get(field))- for child in node.get('children') or []:- visit(child)-- for kind in ('images', 'buffers', 'programs', 'geometry', 'materials'):- for value in each(result.get(kind)):- resource(kind, value)- for node in result['nodes']:- visit(node)- render(result.get('render') or {})- for layer in result.get('animation') or []:- clip = layer.get('clip')- if clip and clip.get('file'):- clip['file'] = asset_path(clip['file'])- for track in each(layer.get('tracks')):- keys = track.get('keys')- if isinstance(keys, dict):- for field in ('times', 'values'):- resource('buffers', keys.get(field))+ # Generated from the Rust scene schema, shared with the TypeScript writer.+ from importlib.resources import files+ graph = json.loads(files(__package__).joinpath('_resource_slots.json').read_text())+ slots = {}++ def walk(value, node, parent=None, key=None):+ if node.get('file') and isinstance(value, str) and parent is not None:+ slots[(id(parent), key)] = (parent, key)+ if 'ref' in node:+ walk(value, graph['defs'][node['ref']])+ for branch in node.get('branches', []):+ walk(value, branch, parent, key)+ if isinstance(value, dict):+ for field, child in node.get('properties', {}).items():+ if field in value:+ walk(value[field], child, value, field)+ if 'values' in node:+ for field, child in value.items():+ walk(child, node['values'], value, field)+ elif isinstance(value, (list, tuple)) and 'items' in node:+ for index, child in enumerate(value):+ walk(child, node['items'], value, index)++ walk(result, graph['root'])+ for parent, key in slots.values():+ parent[key] = asset_path(parent[key])# Immutable sidecar first, then one atomic JSON publication. Retain previous# sidecars for readers that have already opened an earlier JSON snapshot.binary_path = f'{physical}.buffers.{uuid.uuid4()}.bin'@@ -239,7 +190,7 @@ def std(function: str, argument: Any = None, **options: Any) -> Any:if argument is not None and options:raise TypeError('pass an argument or keyword options')result = subprocess.run(- [os.environ.get('VORK_BIN', 'vork'), 'std', function, '-'],+ [_engine(), 'std', function, '-'],input=json.dumps(options if argument is None else argument, allow_nan=False),text=True, capture_output=True,)@@ -249,7 +200,7 @@ def std(function: str, argument: Any = None, **options: Any) -> Any:@_helper_options-def render_arguments(scene: str, out: Union[str, Sequence[str]], *, at: Optional[float] = None,+def _render_arguments(scene: str, out: Union[str, Sequence[str]], *, at: Optional[float] = None,frame_start: Optional[int] = None, frame_end: Optional[int] = None,profile: Optional[str] = None,set: Optional[dict] = None,@@ -293,7 +244,14 @@ class ExposureOutput(TypedDict):exposure: ExposureSummary+class RenderWarning(TypedDict):+ code: str+ requested: dict[str, Any]+ dropped: str++class RenderResult(TypedDict):+ warnings: list[RenderWarning]exposure: list[ExposureOutput]@@ -304,9 +262,10 @@ def render(scene: str, out: Union[str, Sequence[str]], **options: Any) -> Renderset, channels). EXR and control-only outputs have no exposure entry.VORK_BIN selects the executable; the scene file is unchanged."""- subprocess.run([os.environ.get('VORK_BIN', 'vork'), *render_arguments(scene, out, **options)],+ subprocess.run([_engine(), *_render_arguments(scene, out, **options)],check=True)exposure = []+ warnings = []for output in [out] if isinstance(out, str) else out:directory = output.endswith(os.sep) or output.endswith('/')file = not directory and os.path.splitext(output)[1].lower() in ('.png', '.mp4', '.mov', '.exr')@@ -318,9 +277,12 @@ def render(scene: str, out: Union[str, Sequence[str]], **options: Any) -> Renderpath = os.path.join(os.path.dirname(output), sidecar) if file else os.path.join(output, 'meta.json')with open(path, encoding='utf-8') as f:metadata = json.load(f)+ for warning in metadata.get('warnings', []):+ if warning not in warnings:+ warnings.append(warning)if metadata.get('exposure') is not None:exposure.append({'output': output, 'exposure': metadata['exposure']})- return {'exposure': exposure}+ return {'exposure': exposure, 'warnings': warnings}@_helper_optionsdiff --git a/packages/python/vork/_engine.py b/packages/python/vork/_engine.pynew file mode 100644index 0000000..5ac7935--- /dev/null+++ b/packages/python/vork/_engine.py@@ -0,0 +1,45 @@+"""Resolve the project-local native package; archive SDKs retain PATH support."""+import os+import platform+from importlib.util import find_spec+from pathlib import Path+import subprocess+import sys+import threading+++def engine(require_native=False):+ if os.environ.get('VORK_BIN'):+ return os.environ['VORK_BIN']+ target = {('Linux', 'x86_64'): 'linux_x64', ('Darwin', 'arm64'): 'darwin_arm64',+ ('Windows', 'AMD64'): 'windows_x64'}.get((platform.system(), platform.machine()))+ if target is None:+ raise RuntimeError(f'Unsupported vork platform: {platform.system()} {platform.machine()}')+ spec = find_spec('vork_native_' + target)+ if spec and spec.origin:+ return str(Path(spec.origin).parent / 'runtime' / ('vork.exe' if os.name == 'nt' else 'vork'))+ if require_native:+ raise RuntimeError('native package missing; reinstall vork with dependencies from your package index')+ return 'vork'+++def main():+ args = sys.argv[1:]+ if args and args[0] in ('setup', 'render'):+ print('vork: GPU shader compilation can take several minutes on first use. '+ 'Run `vork setup` after upgrading or changing drivers.', file=sys.stderr, flush=True)+ stop = threading.Event()+ def progress():+ while not stop.wait(15):+ print('vork: setup is still compiling GPU shaders…', file=sys.stderr, flush=True)+ if args and args[0] == 'setup':+ threading.Thread(target=progress, daemon=True).start()+ try:+ result = subprocess.run([engine(require_native=True), *args])+ return result.returncode if result.returncode >= 0 else 128 - result.returncode+ except (FileNotFoundError, RuntimeError) as error:+ print(f'vork: {error}', file=sys.stderr)+ return 1++ finally:+ stop.set()diff --git a/packages/python/vork/_resource_slots.json b/packages/python/vork/_resource_slots.jsonnew file mode 100644index 0000000..9e18d23--- /dev/null+++ b/packages/python/vork/_resource_slots.json@@ -0,0 +1,446 @@+{+ "root": {+ "properties": {+ "animation": {+ "items": {+ "ref": "Layer"+ }+ },+ "buffers": {+ "values": {+ "ref": "Buffer"+ }+ },+ "geometry": {+ "values": {+ "ref": "Geometry"+ }+ },+ "images": {+ "values": {+ "ref": "Image"+ }+ },+ "materials": {+ "values": {+ "ref": "Material"+ }+ },+ "nodes": {+ "items": {+ "ref": "Node"+ }+ },+ "programs": {+ "values": {+ "ref": "Program"+ }+ },+ "render": {+ "ref": "Render"+ }+ }+ },+ "defs": {+ "Buffer": {+ "branches": [+ {+ "properties": {+ "file": {+ "file": true+ }+ }+ }+ ]+ },+ "Clip": {+ "properties": {+ "file": {+ "file": true+ }+ }+ },+ "CompositeEntry": {+ "branches": [+ {+ "ref": "NameOr"+ },+ {+ "ref": "CompositeNode"+ }+ ]+ },+ "CompositeNode": {+ "properties": {+ "material": {+ "ref": "NameOr"+ }+ }+ },+ "Geometry": {+ "properties": {+ "attributes": {+ "values": {+ "ref": "NameOr3"+ }+ },+ "count": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "curve_vertex_counts": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "ids": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "indices": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "morphs": {+ "values": {+ "ref": "Morph"+ }+ },+ "widths": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ }+ }+ },+ "GridBinding": {+ "properties": {+ "grid": {+ "ref": "NameOr3"+ }+ }+ },+ "Image": {+ "properties": {+ "file": {+ "file": true+ },+ "render": {+ "branches": [+ {+ "ref": "ImageRender"+ }+ ]+ }+ }+ },+ "ImageRender": {+ "properties": {+ "compositor": {+ "items": {+ "ref": "CompositeEntry"+ }+ }+ }+ },+ "Input": {+ "branches": [+ {+ "ref": "TextureBinding"+ },+ {+ "ref": "GridBinding"+ }+ ]+ },+ "Instances": {+ "properties": {+ "attributes": {+ "values": {+ "ref": "NameOr3"+ }+ },+ "count": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ }+ }+ },+ "Keys": {+ "branches": [+ {+ "properties": {+ "times": {+ "ref": "NameOr3"+ },+ "values": {+ "ref": "NameOr3"+ }+ }+ }+ ]+ },+ "Layer": {+ "branches": [+ {+ "properties": {+ "tracks": {+ "items": {+ "ref": "Track"+ }+ }+ }+ },+ {+ "properties": {+ "clip": {+ "branches": [+ {+ "ref": "Clip"+ }+ ]+ }+ }+ }+ ]+ },+ "Material": {+ "properties": {+ "inputs": {+ "values": {+ "ref": "Input"+ }+ },+ "program": {+ "ref": "NameOr2"+ }+ }+ },+ "Morph": {+ "properties": {+ "NORMAL": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "POSITION": {+ "ref": "NameOr3"+ }+ }+ },+ "NameOr": {+ "branches": [+ {+ "ref": "Material"+ }+ ]+ },+ "NameOr2": {+ "branches": [+ {+ "ref": "Program"+ }+ ]+ },+ "NameOr3": {+ "branches": [+ {+ "ref": "Buffer"+ }+ ]+ },+ "NameOr4": {+ "branches": [+ {+ "ref": "Image"+ }+ ]+ },+ "NameOr5": {+ "branches": [+ {+ "ref": "Geometry"+ }+ ]+ },+ "Node": {+ "branches": [+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ }+ }+ },+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ },+ "geometry": {+ "ref": "NameOr5"+ },+ "instances": {+ "branches": [+ {+ "ref": "Instances"+ }+ ]+ },+ "materials": {+ "items": {+ "ref": "NameOr"+ }+ },+ "skin": {+ "branches": [+ {+ "ref": "Skin"+ }+ ]+ }+ }+ },+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ },+ "file": {+ "file": true+ },+ "materials": {+ "values": {+ "ref": "NameOr"+ }+ }+ }+ },+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ },+ "material": {+ "branches": [+ {+ "ref": "NameOr"+ }+ ]+ }+ }+ },+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ },+ "image": {+ "branches": [+ {+ "ref": "NameOr4"+ }+ ]+ },+ "material": {+ "branches": [+ {+ "ref": "NameOr"+ }+ ]+ }+ }+ }+ ]+ },+ "Program": {+ "branches": [+ {+ "properties": {+ "bindings": {+ "values": {+ "ref": "NameOr3"+ }+ },+ "file": {+ "file": true+ }+ }+ },+ {+ "properties": {+ "bindings": {+ "values": {+ "ref": "NameOr3"+ }+ },+ "source_origin": {+ "file": true+ }+ }+ }+ ]+ },+ "Render": {+ "properties": {+ "compositor": {+ "items": {+ "ref": "CompositeEntry"+ }+ },+ "display": {+ "ref": "NameOr"+ }+ }+ },+ "Skin": {+ "properties": {+ "inverse_bind_matrices": {+ "ref": "NameOr3"+ }+ }+ },+ "TextureBinding": {+ "properties": {+ "image": {+ "ref": "NameOr4"+ }+ }+ },+ "Track": {+ "properties": {+ "keys": {+ "ref": "Keys"+ }+ }+ }+ }+}diff --git a/packages/python/vork/types.py b/packages/python/vork/types.pyindex 4d9fcce..d15e4b7 100644--- a/packages/python/vork/types.py+++ b/packages/python/vork/types.py@@ -80,4 +80,4 @@ Skin = TypedDict('Skin', {'inverse_bind_matrices': Required['NameOr3'], 'joints'SubdivisionSurface = TypedDict('SubdivisionSurface', {'render_levels': int, 'subdivision_type': 'SubdivisionType', 'use_limit_surface': bool}, total=False)TextureBinding = TypedDict('TextureBinding', {'image': Required['NameOr4']}, total=False)Track = TypedDict('Track', {'interpolation': Union['Interpolation', None], 'keys': Required['Keys'], 'path': Required[list[str]]}, total=False)-Scene = TypedDict('Scene', {'animation': list['Layer'], 'buffers': dict[str, 'Buffer'], 'geometry': dict[str, 'Geometry'], 'images': dict[str, 'Image'], 'materials': dict[str, 'Material'], 'nodes': Required[list['Node']], 'programs': dict[str, 'Program'], 'propagation': Union['Propagation', None], 'render': 'Render', 'simulation': Union['Simulation', None], 'version': Required[Literal[2]]}, total=False)+Scene = TypedDict('Scene', {'$schema': Union[str, None], 'animation': list['Layer'], 'buffers': dict[str, 'Buffer'], 'geometry': dict[str, 'Geometry'], 'images': dict[str, 'Image'], 'materials': dict[str, 'Material'], 'nodes': Required[list['Node']], 'programs': dict[str, 'Program'], 'propagation': Union['Propagation', None], 'render': 'Render', 'simulation': Union['Simulation', None], 'version': Required[Literal[2]]}, total=False)diff --git a/packages/ts/README.md b/packages/ts/README.mdindex fd21e84..2cbec35 100644--- a/packages/ts/README.md+++ b/packages/ts/README.md@@ -1,4 +1,4 @@-# @usevoyager/vork+# @voyager-so/vorkRust-generated scene types, JSON Schema and serialization. Node 22.18+; no runtime npm dependencies.Run `npm ci && npm run build`.@@ -9,7 +9,7 @@ and writes them relative to the scene file. Large inline buffers use a sibling bMove the scene together with its referenced resources to preserve those relative paths.For unchanged paths, serialize with `JSON.stringify`. Run the native `vork render`command on the JSON; native validation checks numeric ranges and scene relationships.-The JSON Schema is exported as `@usevoyager/vork/scene.schema.json`.+The JSON Schema is exported as `@voyager-so/vork/scene.schema.json`.Rust scene types are the source of truth. After changing them, run `npm run generate`.`npm run check:generated` fails if either generated artifact is stale.@@ -22,9 +22,8 @@ Field reference: `vork help geometry --all`.The standard library keeps triangulated shape generation (`box`,`sphere`, `cylinder`, `cone`, `torus`, `capsule`, `roundedBox`, `grid`, `revolve`, and the-native `extrude`), uniform-surface-area `scatter`, and the native font loader `text`. These return ordinary-geometry or instance data. See `vork help std`.+native `extrude`) and the native font loader `text`. These return ordinary+buffers and geometry maps. See `vork help std`.`render('shot.json', {out: 'still.png', at: 0, profile: 'std/previs'})` runs `vork render` withrender-time options (`at`, `profile`, `set`, `channels`); the scene file is unchanged.@@ -43,7 +42,10 @@ Readers therefore see a matching pair, including during concurrent saves. Olderare retained for readers holding previous JSON snapshots; interrupted saves can also leaveunreferenced sidecars. Fresh files are private; replacement JSON preserves existing permissions.-`render()` prints the CLI exposure lines and returns `{exposure: [{output, exposure}]}`.+`render()` prints the CLI exposure lines and returns `{exposure: [{output, exposure}], warnings}`.+`warnings` contains `{code, requested, dropped}` records for requested effects+omitted or substituted by the renderer, also printed prominently by the CLI and+written into each render metadata sidecar. Check this array before accepting a render.Each summary contains `frames`, `coverage` (mean alpha), `clipped`, `near_black`, `mean`, and`worst_clipped`/`worst_near_black` (`share`, absolute `frame`). EXR and control-onlyoutputs have no entry. Statistics weight display RGB by alpha; empty coverage gives@@ -53,3 +55,10 @@ retain full precision from the output metadata.Surface programs author emitted light once with OpenPBR `emission_color` and`emission_luminance`; hits and light samples share that evaluation. Use `lit`for authored glow that should not become a sampled light.++Scene JSON may include `"$schema": "https://voyager.so/vork/schema/scene.schema.json"` for editor+completion and validation. This metadata does not affect rendering and is never+fetched by vork. `vork init` includes it automatically. SDK writers preserve an explicit `$schema`+but do not insert one, so 0.1-compatible scenes still load in 0.1. Remove an+explicit `$schema` before using a 0.1 binary. SDK render helpers accept 0.1+metadata without warnings and return an empty warnings list in that case.diff --git a/packages/ts/generate-resource-slots.mjs b/packages/ts/generate-resource-slots.mjsnew file mode 100644index 0000000..90e4b66--- /dev/null+++ b/packages/ts/generate-resource-slots.mjs@@ -0,0 +1,47 @@+// Both writers consume the same graph, derived from the Rust input schema.+import { readFileSync, writeFileSync } from 'node:fs';+const schema = JSON.parse(readFileSync(new URL('scene.schema.json', import.meta.url)));+function graph(schema) {+ if (!schema || typeof schema !== 'object') return {};+ const node = {};+ if (schema.$ref) node.ref = schema.$ref.split('/').at(-1);+ const branches = ['allOf', 'anyOf', 'oneOf'].flatMap(key => (schema[key] ?? []).map(graph));+ if (branches.length) node.branches = branches;+ if (schema.items) node.items = graph(schema.items);+ if (schema.additionalProperties && typeof schema.additionalProperties === 'object') node.values = graph(schema.additionalProperties);+ // Only schema-declared filename properties are paths; opaque input/table names+ // are visited through their value schema, never interpreted as field names.+ if (schema.properties) node.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, value]) =>+ [key, ['file', 'source_origin'].includes(key) && [value.type].flat().includes('string') ? {file: true} : graph(value)]));+ return node;+}+const defs = Object.fromEntries(Object.entries(schema.$defs).map(([key, value]) => [key, graph(value)]));+const root = graph(schema);+// Remove branches that cannot lead to a file, including dead reference cycles.+const live = new Set();+function useful(node) {+ return node.file || (node.ref && live.has(node.ref)) || (node.branches ?? []).some(useful)+ || Object.values(node.properties ?? {}).some(useful) || (node.items && useful(node.items)) || (node.values && useful(node.values));+}+let count;+do { count = live.size; for (const [key, value] of Object.entries(defs)) if (useful(value)) live.add(key); } while (live.size !== count);+function prune(node) {+ if (!useful(node)) return undefined;+ return Object.fromEntries(Object.entries(node).flatMap(([key, value]) => {+ if (key === 'properties') return [[key, Object.fromEntries(Object.entries(value).filter(([, v]) => useful(v)).map(([k,v]) => [k, prune(v)]))]];+ if (key === 'branches') return [[key, value.filter(useful).map(prune)]];+ if (key === 'items' || key === 'values') return useful(value) ? [[key, prune(value)]] : [];+ return [[key, value]];+ }));+}+const result = {root: prune(root), defs: Object.fromEntries(Object.entries(defs).filter(([key]) => live.has(key)).map(([key,value]) => [key,prune(value)]))};+const json = JSON.stringify(result, null, 2) + '\n';+for (const [path, content] of [+ ['src/resource-slots.ts', '// Generated from the Rust scene schema; do not edit.\nexport const resourceSlots = ' + json.trim() + ' as const;\n'],+ ['../python/vork/_resource_slots.json', json],+]) {+ const url = new URL(path, import.meta.url);+ if (process.argv.includes('--check')) {+ if (readFileSync(url, 'utf8') !== content) throw new Error(`${path} is stale`);+ } else writeFileSync(url, content);+}diff --git a/packages/ts/generate-std.mjs b/packages/ts/generate-std.mjsindex 1cce48d..5b24ffd 100644--- a/packages/ts/generate-std.mjs+++ b/packages/ts/generate-std.mjs@@ -2,7 +2,7 @@import ts from 'typescript';import { readFileSync, writeFileSync } from 'node:fs';import { fileURLToPath } from 'node:url';-const modules = ['validate', 'constants', 'math', 'random', 'shapes', 'scatter', 'text', 'extrude'];+const modules = ['validate', 'constants', 'math', 'shapes', 'text', 'extrude'];// Native loaders in crates/vork-std: only their help is generated here.const native = ['text', 'extrude'];const paths = modules.map(name => fileURLToPath(new URL(`src/lib/${name}.ts`, import.meta.url)));@@ -62,9 +62,9 @@ for (const [index, path] of paths.entries()) {const source = program.getSourceFile(path);if (!native.includes(modules[index])) output += ts.transpileModule(source.text, {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext}}).outputText.replace(/^import .*;\s*$/gm, '').replace(/^export \{\};\s*$/gm, '').replace(/\bexport /g, '') + '\n';- if (['validate', 'constants', 'math', 'random'].includes(modules[index])) continue;+ if (['validate', 'constants', 'math'].includes(modules[index])) continue;for (const declaration of source.statements) {- if (ts.isTypeAliasDeclaration(declaration) && ['GeometryFragment','InstanceFragment'].includes(declaration.name.text)) {+ if (ts.isTypeAliasDeclaration(declaration) && ['GeometryFragment'].includes(declaration.name.text)) {const type = checker.getTypeAtLocation(declaration);help += `${declaration.name.text}: {${checker.getPropertiesOfType(type).map(symbol => field(symbol.name,checker.getTypeOfSymbolAtLocation(symbol,symbol.valueDeclaration ?? symbol.declarations[0]),@@ -115,7 +115,7 @@ for (const [index, path] of paths.entries()) {}output += `const stdFunctions = {${entries.join(',\n')}};\nfunction stdEvaluate(name,args) {\n if (!Object.hasOwn(stdFunctions,name)) throw new Error('unknown standard-library function '+name+'; see vork help std');\n const fn=stdFunctions[name];\n if (fn.keys === null) { if (!Array.isArray(args)) throw new TypeError('argument must be an array'); }\n else { checkOptions(args,fn.keys); for (const key of fn.required) if (!Object.hasOwn(args,key)) throw new TypeError('missing option: '+key); }\n return fn.invoke(args);\n}\n`;// The starting page keeps three builders; all other signatures live in the advanced std reference.-const shapeLines = help.split('\n').filter(line => /^(box|sphere|cylinder|cone|torus|capsule|rounded_box|grid|revolve|text|extrude|scatter):/.test(line));+const shapeLines = help.split('\n').filter(line => /^(box|sphere|cylinder|cone|torus|capsule|rounded_box|grid|revolve|text|extrude):/.test(line));const apiShapeLines = shapeLines.filter(line => /^(box|sphere|grid):/.test(line));const indexPath = new URL('../../docs/help/index.md', import.meta.url);const index = readFileSync(indexPath, 'utf8').replace(diff --git a/packages/ts/generate.mjs b/packages/ts/generate.mjsindex a18dbb5..0b638c0 100644--- a/packages/ts/generate.mjs+++ b/packages/ts/generate.mjs@@ -35,6 +35,8 @@ for (const [file, value] of [['scene.schema.json', schemaText], ['src/schema.ts'} else writeFileSync(new URL(file, import.meta.url), value);}+execFileSync(process.execPath, ['packages/ts/generate-resource-slots.mjs', ...(process.argv.includes('--check') ? ['--check'] : [])], {cwd: new URL('../..', import.meta.url), stdio: 'inherit'});+// Rust owns field documentation and defaults as well as the input schema.execFileSync('cargo', ['run', '--quiet', '-p', 'vork-scene', '--example', 'generate-docs', ...(process.argv.includes('--check') ? ['--', '--check'] : [])], {cwd: new URL('../..', import.meta.url), stdio: 'inherit',diff --git a/packages/ts/package-lock.json b/packages/ts/package-lock.jsonindex cc8f547..4a00220 100644--- a/packages/ts/package-lock.json+++ b/packages/ts/package-lock.json@@ -1,12 +1,12 @@{- "name": "@usevoyager/vork",- "version": "0.1.0",+ "name": "@voyager-so/vork",+ "version": "0.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {- "name": "@usevoyager/vork",- "version": "0.1.0",+ "name": "@voyager-so/vork",+ "version": "0.2.0","license": "SEE LICENSE IN LICENSE","devDependencies": {"@types/node": "^22.0.0",diff --git a/packages/ts/package.json b/packages/ts/package.jsonindex 3700add..4041f1b 100644--- a/packages/ts/package.json+++ b/packages/ts/package.json@@ -1,6 +1,6 @@{- "name": "@usevoyager/vork",- "version": "0.1.0",+ "name": "@voyager-so/vork",+ "version": "0.2.0","description": "Rust-generated scene types, JSON Schema and serialization for vork","type": "module","license": "SEE LICENSE IN LICENSE",diff --git a/packages/ts/scene.schema.json b/packages/ts/scene.schema.jsonindex aa721e8..ecd81a0 100644--- a/packages/ts/scene.schema.json+++ b/packages/ts/scene.schema.json@@ -1554,7 +1554,7 @@"type": "null"}],- "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top",+ "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translation","x-help-path": "node.target","x-source": "Blender Track To constraint (vork target shorthand)"},@@ -1690,9 +1690,9 @@"$ref": "#/$defs/NameOr"},"type": "array",- "x-help": "(material-name|inline material)[]; empty = default std/openpbr with roughness 0.5",+ "x-help": "(material-name|inline material)[]; empty = default std/openpbr with roughness 0.3","x-help-path": "node.mesh.materials",- "x-source": "vork (explicit contract/technique choice)"+ "x-source": "OpenPBR Surface 1.1.1"},"morph_weights": {"additionalProperties": {@@ -1775,7 +1775,7 @@"type": "null"}],- "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top",+ "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translation","x-help-path": "node.target","x-source": "Blender Track To constraint (vork target shorthand)"},@@ -1971,7 +1971,7 @@"type": "null"}],- "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top",+ "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translation","x-help-path": "node.target","x-source": "Blender Track To constraint (vork target shorthand)"},@@ -2165,7 +2165,7 @@"type": "null"}],- "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top",+ "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translation","x-help-path": "node.target","x-source": "Blender Track To constraint (vork target shorthand)"},@@ -2467,7 +2467,7 @@"type": "null"}],- "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top",+ "x-help": "node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translation","x-help-path": "node.target","x-source": "Blender Track To constraint (vork target shorthand)"},@@ -3185,9 +3185,19 @@"type": "string"}},+ "$id": "https://voyager.so/vork/schema/scene.schema.json","$schema": "https://json-schema.org/draft/2020-12/schema","additionalProperties": false,"properties": {+ "$schema": {+ "description": "Editor JSON Schema address; metadata only, never fetched by the renderer.",+ "type": [+ "string",+ "null"+ ],+ "x-help": "string; editor schema URL",+ "x-help-path": "scene.$schema"+ },"animation": {"default": [],"items": {@@ -3478,7 +3488,7 @@"node.instances (mesh): instances|null","node.instances.attributes (mesh): equal-length buffers: TRANSLATION vec3, ROTATION vec4 (xyzw), SCALE vec3 (omitted = identity; any zero world-scale component hides the instance), time_offset f32, pass_index u32, custom columns bind to material inputs","node.instances.count (mesh): one-element u32 compute buffer; zero to attribute capacity; overflow rejects the exposure",- "node.materials (mesh): (material-name|inline material)[]; empty = default std/openpbr with roughness 0.5; default []",+ "node.materials (mesh): (material-name|inline material)[]; empty = default std/openpbr with roughness 0.3; default []","node.morph_weights (mesh): {name:number}; default {}","node.skin (mesh): skin|null","node.skin.inverse_bind_matrices (mesh): mat4-buffer-name|inline buffer",@@ -3487,7 +3497,7 @@"node.pass_index: u32|null; 1..65535; object ID","node.rotation: [x,y,z,w] quaternion | {euler:[x,y,z]} (Blender XYZ); default [0,0,0,1]","node.scale: [x,y,z]; any zero world-scale component hides geometry, including children; default [1,1,1]",- "node.target: node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top",+ "node.target: node-name|[x,y,z]|null; aims -Z, world Y up; rotation is an offset on top; structural, not animatable: aim at a named node and animate its translation","node.translation: [x,y,z]; parent frame; default [0,0,0]","node.visible: bool; false hides the subtree and disables its lights; animatable (step); default true","node.visible_camera: bool; default true",@@ -3519,6 +3529,7 @@"render.motion_blur.shutter: number; frames; default 0.5","render.resolution: uvec2; default [1920,1080]","render.root: node-name|null; only this subtree draws and is lit; objects outside still cast shadows; null = whole scene; default null",+ "scene.$schema: string; editor schema URL","scene.animation: layer[]; default []","scene.buffers: {name:buffer}; default {}","scene.geometry: {name:geometry}; default {}",diff --git a/packages/ts/src/index.ts b/packages/ts/src/index.tsindex 0d67511..1e1fd6d 100644--- a/packages/ts/src/index.ts+++ b/packages/ts/src/index.ts@@ -1,6 +1,7 @@import { mkdir, open, rename, rm, realpath, lstat } from 'node:fs/promises';import { randomUUID } from 'node:crypto';import { dirname, resolve, relative, basename } from 'node:path';+import { resourceSlots } from './resource-slots.js';import type { Scene } from './schema.js';import { externalBuffers } from './lib/buffers.js';export type * from './schema.js';@@ -21,49 +22,29 @@ async function withAssetPaths(value: Scene, baseDir: string, sceneDir: string):return relative(sceneDir, resolve(await fileIdentity(dirname(source)), basename(source)));};const result = structuredClone(value);- // One declaration of resource-bearing fields. `*` means array items or- // opaque table values, never a resource name interpreted as a field.- const edges: Record<string, [string, string][]> = {- scene: [['nodes.*','node'],['render','render'],['animation.*','layer'],- ...['images','buffers','programs','geometry','materials'].map(kind => [`${kind}.*`,kind] as [string,string])],- node: [['children.*','node'],['geometry','geometry'],['materials.*','materials'],- ['instances.count','buffers'],['instances.attributes.*','buffers'],['skin.inverse_bind_matrices','buffers'],- ['image','images'],['material','materials']],- geometry: [['indices','buffers'],['curve_vertex_counts','buffers'],['widths','buffers'],- ['attributes.*','buffers'],['morphs.*.POSITION','buffers'],['morphs.*.NORMAL','buffers']],- materials: [['program','programs'],['inputs.*','input']],- input: [['image','images'],['grid','buffers']],- images: [['render','render']],- render: [['compositor.*','materials'],['compositor_per_step.*','materials'],['display','materials']],- programs: [['bindings.*','buffers']],- layer: [['tracks.*.keys.times','buffers'],['tracks.*.keys.values','buffers']],- };- const files: Record<string, string[]> = {- buffers:['file'], images:['file'], programs:['file','source_origin'],- node:['file'], layer:['clip.file'],- };- type ObjectValue = Record<string, any>;- const slots = async (value: any, path: string[], visit: (parent: ObjectValue, key: string) => Promise<void>): Promise<void> => {+ const files = new Map<object, Set<string>>();+ type Graph = {file?: boolean; ref?: string; branches?: readonly Graph[];+ properties?: Record<string, Graph>; items?: Graph; values?: Graph};+ const defs: Record<string, Graph> = resourceSlots.defs;+ const walk = (value: any, node: Graph, parent?: any, key?: string): void => {+ if (node.file && parent && key !== undefined && typeof value === 'string') {+ if (!files.has(parent)) files.set(parent, new Set());+ files.get(parent)!.add(key);+ }+ if (node.ref) walk(value, defs[node.ref]!);+ for (const branch of node.branches ?? []) walk(value, branch, parent, key);if (!value || typeof value !== 'object') return;- const head = path[0]!;- const tail = path.slice(1);- for (const key of head === '*' ? Object.keys(value) : [head]) {- if (tail.length) await slots(value[key],tail,visit);- else await visit(value,key);+ for (const [key, child] of Object.entries(node.properties ?? {})) {+ if (Object.hasOwn(value, key)) walk(value[key], child, value, key);}+ if (Array.isArray(value) && node.items) value.forEach((item, key) => walk(item, node.items!, value, String(key)));+ if (!Array.isArray(value) && node.values) for (const key of Object.keys(value)) walk(value[key], node.values, value, key);};- const seen = new Set<object>();- const resource = async (kind: string, value: any): Promise<void> => {- if (!value || typeof value !== 'object' || Array.isArray(value) || seen.has(value)) return;- seen.add(value);- for (const path of files[kind] ?? []) await slots(value,path.split('.'),async (parent,key) => {- if (typeof parent[key] === 'string') parent[key] = await assetPath(parent[key]);- });- for (const [path,target] of edges[kind] ?? []) await slots(value,path.split('.'),async (parent,key) => {- await resource(target,parent[key]);- });- };- await resource('scene',result);+ walk(result, resourceSlots.root);+ for (const [parent, keys] of files) for (const key of keys) {+ const object = parent as Record<string, string>;+ object[key] = await assetPath(object[key]!);+ }return result;}/** Write scene JSON with relative resource paths and a binary sidecar for large buffers. */@@ -106,8 +87,7 @@ export async function writeScene(value: Scene, path: string, baseDir = process.cexport { box, sphere, cylinder, cone, torus, capsule, roundedBox, grid, revolve } from './lib/shapes.js';export type { GeometryFragment } from './lib/shapes.js';-export { scatter, type InstanceFragment } from './lib/scatter.js';export { text, type TextOptions } from './lib/text.js';export { extrude, type ExtrudeOptions } from './lib/extrude.js';-export { render, renderArguments, type RenderOptions, type RenderResult, type ExposureSummary } from './lib/render.js';+export { render, type RenderOptions, type RenderResult, type RenderWarning, type ExposureSummary } from './lib/render.js';export { environmentImage, sky, type EnvironmentImageOptions, type EnvironmentFragment } from './lib/environment.js';diff --git a/packages/ts/src/lib/cli.ts b/packages/ts/src/lib/cli.tsindex 6432879..dba28c3 100644--- a/packages/ts/src/lib/cli.ts+++ b/packages/ts/src/lib/cli.ts@@ -1,9 +1,10 @@+import { engine } from './engine.js';import { execFileSync } from 'node:child_process';/** Run `vork std FUNCTION -` (VORK_BIN overrides the executable); failures carry the CLI's message. */export function stdCommand(name: string, argument: unknown): unknown {try {- return JSON.parse(execFileSync(process.env.VORK_BIN ?? 'vork', ['std', name, '-'], {+ return JSON.parse(execFileSync(engine(), ['std', name, '-'], {input: JSON.stringify(argument), encoding: 'utf8', maxBuffer: 64 * 1024 * 1024,stdio: ['pipe', 'pipe', 'pipe'],}));diff --git a/packages/ts/src/lib/constants.ts b/packages/ts/src/lib/constants.tsindex 7fa52ce..1e45b12 100644--- a/packages/ts/src/lib/constants.ts+++ b/packages/ts/src/lib/constants.ts@@ -8,14 +8,5 @@ export const ROUNDED_BOX_SEGMENTS = 8;* turning by more than this is sharp (split normals); gentler corners share a smooth normal.* vork-std's native extrude repeats it (crates/vork-std/src/extrude.rs). */export const SMOOTH_ANGLE_DEGREES = 30;-/** Numerical Recipes uint32 LCG: reproducible seeded sampling across host languages. */-export const LCG_MULTIPLIER = 1664525;-export const LCG_INCREMENT = 1013904223;-/** Exact uint32 range used to normalize seeded random values to [0,1). */-export const UINT32_RANGE = 4294967296;-/** MurmurHash3 fmix32 avalanche constants decorrelate adjacent author seeds. */-export const SEED_MIX_MULTIPLIER_A = 0x85ebca6b;-export const SEED_MIX_MULTIPLIER_B = 0xc2b2ae35;-export const SEED_MIX_SHIFTS = [16,13,16] as const;/** SDK authoring choice: externalize buffers of at least 4 KiB to keep scene JSON readable. */export const BINARY_BUFFER_MIN_BYTES = 4096;diff --git a/packages/ts/src/lib/engine.ts b/packages/ts/src/lib/engine.tsnew file mode 100644index 0000000..a463b2a--- /dev/null+++ b/packages/ts/src/lib/engine.ts@@ -0,0 +1,25 @@+import { createRequire } from 'node:module';+import { readFileSync, existsSync } from 'node:fs';++/** Resolve beside this SDK so project dependencies work without a global install. */+export function engine(): string {+ if (process.env.VORK_BIN) return process.env.VORK_BIN;+ const target = `${process.platform}-${process.arch}`;+ if (!['linux-x64', 'darwin-arm64', 'win32-x64'].includes(target)) {+ throw new Error(`Unsupported vork platform: ${target}`);+ }+ const name = target.replace('win32', 'windows');+ try {+ return createRequire(import.meta.url).resolve(`@voyager-so/vork-${name}/runtime/${process.platform === 'win32' ? 'vork.exe' : 'vork'}`);+ } catch {+ // Registry dist/lib and archive lib have different depths.+ for (const path of ['../package.json', '../../package.json']) {+ const url = new URL(path, import.meta.url);+ if (existsSync(url) && JSON.parse(readFileSync(url, 'utf8')).optionalDependencies) {+ throw new Error('vork native package missing; reinstall @voyager-so/vork with --include=optional');+ }+ }+ // Archive/source SDKs retain the existing PATH install route.+ return 'vork';+ }+}diff --git a/packages/ts/src/lib/environment.ts b/packages/ts/src/lib/environment.tsindex 8768d9d..48feeea 100644--- a/packages/ts/src/lib/environment.ts+++ b/packages/ts/src/lib/environment.ts@@ -1,3 +1,4 @@+import { checkOptions } from './validate.js';import { stdCommand } from './cli.js';import type { Scene } from '../schema.js';@@ -8,13 +9,17 @@ export interface EnvironmentImageOptions {name?: string;threshold?: number;fps?: number;- color_space?: 'sRGB' | 'Linear Rec.709' | 'Non-Color';+ colorSpace?: 'sRGB' | 'Linear Rec.709' | 'Non-Color';}/** Preprocess HDR lighting into an ordinary image program and declared sun. */export function environmentImage(options: EnvironmentImageOptions): EnvironmentFragment {- return stdCommand('environment', options) as EnvironmentFragment;+ checkOptions(options, ['file','output','name','threshold','fps','colorSpace']);+ const {colorSpace, ...rest} = options;+ return stdCommand('environment', {...rest, color_space: colorSpace}) as EnvironmentFragment;}/** Nishita atmosphere and an ordinary solar emitter. */-export function sky(options: {name?: string; sun_elevation?: number; sun_rotation?: number; altitude?: number; air_density?: number; aerosol_density?: number; ozone_density?: number; sun_size?: number; sun_intensity?: number} = {}): EnvironmentFragment {- return stdCommand('sky', options) as EnvironmentFragment;+export function sky(options: {name?: string; sunElevation?: number; sunRotation?: number; altitude?: number; airDensity?: number; aerosolDensity?: number; ozoneDensity?: number; sunSize?: number; sunIntensity?: number} = {}): EnvironmentFragment {+ checkOptions(options, ['name','altitude','sunElevation','sunRotation','airDensity','aerosolDensity','ozoneDensity','sunSize','sunIntensity']);+ const {sunElevation, sunRotation, airDensity, aerosolDensity, ozoneDensity, sunSize, sunIntensity, ...rest} = options;+ return stdCommand('sky', {...rest, sun_elevation: sunElevation, sun_rotation: sunRotation, air_density: airDensity, aerosol_density: aerosolDensity, ozone_density: ozoneDensity, sun_size: sunSize, sun_intensity: sunIntensity}) as EnvironmentFragment;}diff --git a/packages/ts/src/lib/random.ts b/packages/ts/src/lib/random.tsdeleted file mode 100644index d558fcd..0000000--- a/packages/ts/src/lib/random.ts+++ /dev/null@@ -1,10 +0,0 @@-import { LCG_MULTIPLIER, LCG_INCREMENT, UINT32_RANGE, SEED_MIX_MULTIPLIER_A, SEED_MIX_MULTIPLIER_B, SEED_MIX_SHIFTS } from './constants.js';-/** Internal deterministic generator; fmix32 decorrelates adjacent author seeds before the LCG. */-export function seededRandom(seed:number):()=>number {- if(!Number.isInteger(seed)||seed<0||seed>=UINT32_RANGE) throw new RangeError('seed must be a uint32');- let state=seed;- state=Math.imul(state^(state>>>SEED_MIX_SHIFTS[0]),SEED_MIX_MULTIPLIER_A);- state=Math.imul(state^(state>>>SEED_MIX_SHIFTS[1]),SEED_MIX_MULTIPLIER_B);- state=(state^(state>>>SEED_MIX_SHIFTS[2]))>>>0;- return ()=>{state=(Math.imul(state,LCG_MULTIPLIER)+LCG_INCREMENT)>>>0;return state/UINT32_RANGE;};-}diff --git a/packages/ts/src/lib/render.ts b/packages/ts/src/lib/render.tsindex d35887c..f6b6f39 100644--- a/packages/ts/src/lib/render.ts+++ b/packages/ts/src/lib/render.ts@@ -1,3 +1,4 @@+import { engine } from './engine.js';import {callKeys} from './call-keys.js';import { execFileSync } from 'node:child_process';import { readFileSync } from 'node:fs';@@ -31,7 +32,14 @@ export interface ExposureSummary {worst_clipped: { share: number; frame: number } | null;worst_near_black: { share: number; frame: number } | null;}+export interface RenderWarning {+ code: string;+ requested: Record<string, unknown>;+ dropped: string;+}export interface RenderResult {+ /** Requested effects omitted or substituted by the renderer. */+ warnings: RenderWarning[];/** Display-image statistics per output; EXR and control-only outputs have no entry. */exposure: { output: string; exposure: ExposureSummary }[];}@@ -39,8 +47,9 @@ export interface RenderResult {* Options are render-time choices; the scene file is unchanged.*/export function render(scene: string, options: RenderOptions): RenderResult {- execFileSync(process.env.VORK_BIN ?? 'vork', renderArguments(scene, options), { stdio: ['ignore', 'inherit', 'inherit'] });+ execFileSync(engine(), renderArguments(scene, options), { stdio: ['ignore', 'inherit', 'inherit'] });const exposure: RenderResult['exposure'] = [];+ const warnings = new Map<string, RenderWarning>();for (const output of typeof options.out === 'string' ? [options.out] : options.out) {const directory = output.endsWith('/') || output.endsWith(sep);const file = !directory && ['.png','.mp4','.mov','.exr'].includes(extname(output).toLowerCase());@@ -49,12 +58,13 @@ export function render(scene: string, options: RenderOptions): RenderResult {if (index >= 0) name = name.slice(0,index).replace(/[._-]+$/, '') + name.slice(index+4);const sidecar = name.startsWith('.') && !name.slice(1).includes('.') ? 'meta.json' : `${name}.meta.json`;const metadata = JSON.parse(readFileSync(file ? join(dirname(output),sidecar) : join(output,'meta.json'), 'utf8'));+ for (const warning of metadata.warnings ?? []) warnings.set(JSON.stringify(warning), warning);if (metadata.exposure != null) exposure.push({output, exposure: metadata.exposure});}- return {exposure};+ return {exposure, warnings: [...warnings.values()]};}/** The `vork render` command line for a scene file and options. */-export function renderArguments(scene: string, options: RenderOptions): string[] {+function renderArguments(scene: string, options: RenderOptions): string[] {checkOptions(options, ['out','at','frameStart','frameEnd','profile','set','channels']);const args = ['render', scene];for (const out of typeof options.out === 'string' ? [options.out] : options.out) args.push('--out', out);diff --git a/packages/ts/src/lib/scatter.ts b/packages/ts/src/lib/scatter.tsdeleted file mode 100644index 79e3ff3..0000000--- a/packages/ts/src/lib/scatter.ts+++ /dev/null@@ -1,102 +0,0 @@-import type { Scene, Node } from '../schema.js';-import type { GeometryFragment } from './shapes.js';-import { checkName, checkOptions } from './validate.js';-import { seededRandom } from './random.js';-import { unit, cross } from './math.js';-type Vec3 = readonly [number, number, number];--type Mesh = Extract<Node, {type: 'mesh'}>;-export type InstanceFragment = {buffers: NonNullable<Scene['buffers']>; instances: NonNullable<Mesh['instances']>};--function positiveInteger(value: number, field: string): number {- if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${field} must be a positive safe integer`);- return value;-}-function finish(name: string, transforms: number[][]): InstanceFragment {- checkName(name, 'instance name');- const translation = `${name}_translation`, rotation = `${name}_rotation`;- const quaternions = transforms.map(m => {- const diagonal = [m[0]!,m[5]!,m[10]!];- const trace = diagonal[0]!+diagonal[1]!+diagonal[2]!;- const q = [0,0,0,0];- if (trace > 0) {- const s = 2*Math.sqrt(1+trace);- q[0]=(m[6]!-m[9]!)/s; q[1]=(m[8]!-m[2]!)/s; q[2]=(m[1]!-m[4]!)/s; q[3]=s/4;- } else {- const i = diagonal.indexOf(Math.max(...diagonal)), j=(i+1)%3, k=(i+2)%3;- const s = 2*Math.sqrt(1+diagonal[i]!-diagonal[j]!-diagonal[k]!);- q[i]=s/4; q[j]=(m[j*4+i]!+m[i*4+j]!)/s; q[k]=(m[k*4+i]!+m[i*4+k]!)/s;- q[3]=(m[j*4+k]!-m[k*4+j]!)/s;- }- const length=Math.hypot(...q);- return q.map(v=>v/length);- });- return {buffers: {- [translation]: {type:'vec3', data:transforms.map(m=>m.slice(12,15))},- [rotation]: {type:'vec4', data:quaternions},- }, instances:{attributes:{TRANSLATION:translation,ROTATION:rotation}}};-}-/** Uniform area sampling over one inline triangle geometry; local +Y follows the face normal.- * Transforms use the source geometry's local space; give the instanced node the surface- * node's transform, or parent it under that node. The seed is a uint32. */-export function scatter(onGeometry: GeometryFragment, count: number, seed: number, name?:string): InstanceFragment {- positiveInteger(count, 'count');- const random = seededRandom(seed);- const geometries = Object.values(onGeometry.geometry);- if (geometries.length !== 1) throw new RangeError('scatter requires exactly one geometry');- const geometry = geometries[0]!;- name ??= `${Object.keys(onGeometry.geometry)[0]!}_scatter`;- checkName(name, 'instance name');- if (geometry.topology !== undefined && geometry.topology !== 'triangles') throw new RangeError('scatter requires triangle topology');- const position = geometry.attributes.POSITION!;- const source = typeof position === 'string' ? onGeometry.buffers[position] : position;- if (!source || source.type !== 'vec3' || !source.data || source.file) throw new RangeError('scatter requires inline vec3 positions');- const numbers = (value: unknown): number[] => {- if (typeof value === 'number' && Number.isFinite(value)) return [value];- if (Array.isArray(value)) return value.flatMap(numbers);- throw new RangeError('scatter buffers require finite numeric data');- };- if ((source.offset ?? 0) !== 0 || source.count != null) throw new RangeError('inline scatter buffers cannot have offset/count');- const positionRows = Array.from(source.data as readonly unknown[], numbers);- if (!positionRows.every(row => row.length === 3)) throw new RangeError('scatter positions require vec3 elements');- const positions = positionRows.flat();- if (positions.length % 3 !== 0) throw new RangeError('scatter positions require complete vec3 elements');- let indices: number[];- if (geometry.indices) {- const buffer = typeof geometry.indices === 'string' ? onGeometry.buffers[geometry.indices] : geometry.indices;- if (!buffer || buffer.type !== 'u32' || !buffer.data || buffer.file) throw new RangeError('scatter requires inline u32 indices');- if ((buffer.offset ?? 0) !== 0 || buffer.count != null) throw new RangeError('inline scatter buffers cannot have offset/count');- const rows = Array.from(buffer.data as readonly unknown[], numbers);- if (!rows.every(row => row.length === 1)) throw new RangeError('scatter indices require scalar elements');- indices = rows.flat();- } else indices = Array.from({length:positions.length/3}, (_,i) => i);- if (indices.length % 3 !== 0 || !indices.every(i => Number.isInteger(i) && i >= 0 && i < positions.length/3))- throw new RangeError('scatter indices require complete triangles of valid vertex indices');- const vertex = (i:number):Vec3 => positions.slice(i*3,i*3+3) as [number,number,number];- const sub = (a:Vec3,b:Vec3):Vec3 => a.map((v,k) => v-b[k]!) as [number,number,number];- const triangles: {a:Vec3;b:Vec3;c:Vec3;normal:Vec3;end:number}[] = [];- let area = 0;- for (let i=0;i<indices.length;i+=3) {- const a=vertex(indices[i]!),b=vertex(indices[i+1]!),c=vertex(indices[i+2]!);- const normal=cross(sub(b,a),sub(c,a)), weight=Math.hypot(...normal)/2;- if (!Number.isFinite(weight)) throw new RangeError('scatter triangle area is not finite');- if (weight === 0) continue;- area += weight;- if (!Number.isFinite(area)) throw new RangeError('scatter surface area is not finite');- triangles.push({a,b,c,normal:unit(normal),end:area});- }- if (area === 0) throw new RangeError('scatter requires nonzero surface area');- const transforms:number[][]=[];- for (let i=0;i<count;i++) {- const target=random()*area;- let lo=0,hi=triangles.length-1;- while (lo<hi) { const mid=(lo+hi)>>>1; if (triangles[mid]!.end<=target) lo=mid+1; else hi=mid; }- const {a,b,c,normal}=triangles[lo]!;- const u=Math.sqrt(random()),v=random();- const p=a.map((x,k) => x*(1-u)+b[k]!*u*(1-v)+c[k]!*u*v) as [number,number,number];- const reference:Vec3 = Math.abs(normal[0]) < Math.abs(normal[2]) ? [1,0,0] : [0,0,1];- const right=unit(cross(normal,reference)), forward=cross(right,normal);- transforms.push([...right,0,...normal,0,...forward,0,...p,1]);- }- return finish(name, transforms);-}diff --git a/packages/ts/src/resource-slots.ts b/packages/ts/src/resource-slots.tsnew file mode 100644index 0000000..683fdf7--- /dev/null+++ b/packages/ts/src/resource-slots.ts@@ -0,0 +1,447 @@+// Generated from the Rust scene schema; do not edit.+export const resourceSlots = {+ "root": {+ "properties": {+ "animation": {+ "items": {+ "ref": "Layer"+ }+ },+ "buffers": {+ "values": {+ "ref": "Buffer"+ }+ },+ "geometry": {+ "values": {+ "ref": "Geometry"+ }+ },+ "images": {+ "values": {+ "ref": "Image"+ }+ },+ "materials": {+ "values": {+ "ref": "Material"+ }+ },+ "nodes": {+ "items": {+ "ref": "Node"+ }+ },+ "programs": {+ "values": {+ "ref": "Program"+ }+ },+ "render": {+ "ref": "Render"+ }+ }+ },+ "defs": {+ "Buffer": {+ "branches": [+ {+ "properties": {+ "file": {+ "file": true+ }+ }+ }+ ]+ },+ "Clip": {+ "properties": {+ "file": {+ "file": true+ }+ }+ },+ "CompositeEntry": {+ "branches": [+ {+ "ref": "NameOr"+ },+ {+ "ref": "CompositeNode"+ }+ ]+ },+ "CompositeNode": {+ "properties": {+ "material": {+ "ref": "NameOr"+ }+ }+ },+ "Geometry": {+ "properties": {+ "attributes": {+ "values": {+ "ref": "NameOr3"+ }+ },+ "count": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "curve_vertex_counts": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "ids": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "indices": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "morphs": {+ "values": {+ "ref": "Morph"+ }+ },+ "widths": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ }+ }+ },+ "GridBinding": {+ "properties": {+ "grid": {+ "ref": "NameOr3"+ }+ }+ },+ "Image": {+ "properties": {+ "file": {+ "file": true+ },+ "render": {+ "branches": [+ {+ "ref": "ImageRender"+ }+ ]+ }+ }+ },+ "ImageRender": {+ "properties": {+ "compositor": {+ "items": {+ "ref": "CompositeEntry"+ }+ }+ }+ },+ "Input": {+ "branches": [+ {+ "ref": "TextureBinding"+ },+ {+ "ref": "GridBinding"+ }+ ]+ },+ "Instances": {+ "properties": {+ "attributes": {+ "values": {+ "ref": "NameOr3"+ }+ },+ "count": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ }+ }+ },+ "Keys": {+ "branches": [+ {+ "properties": {+ "times": {+ "ref": "NameOr3"+ },+ "values": {+ "ref": "NameOr3"+ }+ }+ }+ ]+ },+ "Layer": {+ "branches": [+ {+ "properties": {+ "tracks": {+ "items": {+ "ref": "Track"+ }+ }+ }+ },+ {+ "properties": {+ "clip": {+ "branches": [+ {+ "ref": "Clip"+ }+ ]+ }+ }+ }+ ]+ },+ "Material": {+ "properties": {+ "inputs": {+ "values": {+ "ref": "Input"+ }+ },+ "program": {+ "ref": "NameOr2"+ }+ }+ },+ "Morph": {+ "properties": {+ "NORMAL": {+ "branches": [+ {+ "ref": "NameOr3"+ }+ ]+ },+ "POSITION": {+ "ref": "NameOr3"+ }+ }+ },+ "NameOr": {+ "branches": [+ {+ "ref": "Material"+ }+ ]+ },+ "NameOr2": {+ "branches": [+ {+ "ref": "Program"+ }+ ]+ },+ "NameOr3": {+ "branches": [+ {+ "ref": "Buffer"+ }+ ]+ },+ "NameOr4": {+ "branches": [+ {+ "ref": "Image"+ }+ ]+ },+ "NameOr5": {+ "branches": [+ {+ "ref": "Geometry"+ }+ ]+ },+ "Node": {+ "branches": [+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ }+ }+ },+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ },+ "geometry": {+ "ref": "NameOr5"+ },+ "instances": {+ "branches": [+ {+ "ref": "Instances"+ }+ ]+ },+ "materials": {+ "items": {+ "ref": "NameOr"+ }+ },+ "skin": {+ "branches": [+ {+ "ref": "Skin"+ }+ ]+ }+ }+ },+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ },+ "file": {+ "file": true+ },+ "materials": {+ "values": {+ "ref": "NameOr"+ }+ }+ }+ },+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ },+ "material": {+ "branches": [+ {+ "ref": "NameOr"+ }+ ]+ }+ }+ },+ {+ "properties": {+ "children": {+ "items": {+ "ref": "Node"+ }+ },+ "image": {+ "branches": [+ {+ "ref": "NameOr4"+ }+ ]+ },+ "material": {+ "branches": [+ {+ "ref": "NameOr"+ }+ ]+ }+ }+ }+ ]+ },+ "Program": {+ "branches": [+ {+ "properties": {+ "bindings": {+ "values": {+ "ref": "NameOr3"+ }+ },+ "file": {+ "file": true+ }+ }+ },+ {+ "properties": {+ "bindings": {+ "values": {+ "ref": "NameOr3"+ }+ },+ "source_origin": {+ "file": true+ }+ }+ }+ ]+ },+ "Render": {+ "properties": {+ "compositor": {+ "items": {+ "ref": "CompositeEntry"+ }+ },+ "display": {+ "ref": "NameOr"+ }+ }+ },+ "Skin": {+ "properties": {+ "inverse_bind_matrices": {+ "ref": "NameOr3"+ }+ }+ },+ "TextureBinding": {+ "properties": {+ "image": {+ "ref": "NameOr4"+ }+ }+ },+ "Track": {+ "properties": {+ "keys": {+ "ref": "Keys"+ }+ }+ }+ }+} as const;diff --git a/packages/ts/src/schema.ts b/packages/ts/src/schema.tsindex fbde599..17d068b 100644--- a/packages/ts/src/schema.ts+++ b/packages/ts/src/schema.ts@@ -113,6 +113,10 @@ export type AovType = "value" | "color";export type MotionBlurPosition = "start" | "center" | "end";export interface Scene {+ /**+ * Editor JSON Schema address; metadata only, never fetched by the renderer.+ */+ $schema?: string | null;animation?: Layer[];buffers?: {[k: string]: Buffer;diff --git a/packages/ts/test/environment-options.test.mjs b/packages/ts/test/environment-options.test.mjsnew file mode 100644index 0000000..be8cf6d--- /dev/null+++ b/packages/ts/test/environment-options.test.mjs@@ -0,0 +1,28 @@+import assert from 'node:assert/strict';+import {test} from 'node:test';+import {mkdtempSync, writeFileSync, chmodSync, rmSync} from 'node:fs';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {environmentImage, sky} from '../dist/index.js';++test('environment helpers lower camelCase options to CLI JSON and reject aliases', () => {+ const dir = mkdtempSync(join(tmpdir(), 'vork-options-'));+ const binary = join(dir, 'vork');+ const previous = process.env.VORK_BIN;+ writeFileSync(binary, '#!/usr/bin/env node\nprocess.stdin.pipe(process.stdout);\n');+ chmodSync(binary, 0o755);+ process.env.VORK_BIN = binary;+ try {+ assert.deepEqual(environmentImage({file:'sky.exr', output:'weight.exr', colorSpace:'Non-Color', fps:30}),+ {file:'sky.exr', output:'weight.exr', color_space:'Non-Color', fps:30});+ assert.deepEqual(sky({sunElevation:0.5,sunRotation:1,airDensity:2,aerosolDensity:3,ozoneDensity:4,sunSize:5,sunIntensity:6,altitude:7}),+ {sun_elevation:0.5,sun_rotation:1,air_density:2,aerosol_density:3,ozone_density:4,sun_size:5,sun_intensity:6,altitude:7});+ assert.deepEqual(sky(), {});+ assert.throws(() => environmentImage({file:'x',output:'y',color_space:'sRGB'}), /unknown option/);+ for (const key of ['sun_elevation','sun_rotation','air_density','aerosol_density','ozone_density','sun_size','sun_intensity'])+ assert.throws(() => sky({[key]:1}), /unknown option/);+ } finally {+ if (previous === undefined) delete process.env.VORK_BIN; else process.env.VORK_BIN = previous;+ rmSync(dir, {recursive:true,force:true});+ }+});diff --git a/packages/ts/test/kernel-validation.test.mjs b/packages/ts/test/kernel-validation.test.mjsindex 2ca0579..80bcc4d 100644--- a/packages/ts/test/kernel-validation.test.mjs+++ b/packages/ts/test/kernel-validation.test.mjs@@ -14,13 +14,20 @@ const validate = scenes => spawnSync('cargo', ['run','--quiet','-p','vork-scene'});const mesh = geometry => ({version:2,...geometry,nodes:[{type:'camera',name:'camera'},{type:'mesh',geometry:Object.keys(geometry.geometry)[0]}]});+test('SDK no longer exports scatter', () => {+ assert.equal('scatter' in sdk, false);+});+test('SDK geometry engines emit fragments accepted by the Rust kernel', async () => {const fixtures=[];for (const shape of ['box','sphere','cylinder','cone','torus','capsule','roundedBox','grid'])fixtures.push(mesh(sdk[shape](shape)));fixtures.push(mesh(sdk.revolve('revolve',{profile:[[0,0],[1,0],[0.5,1],[0,1.2]]})));- const geometry=sdk.grid('surface'), instances=sdk.scatter(geometry,3,7);- fixtures.push({version:2,...geometry,buffers:{...geometry.buffers,...instances.buffers},nodes:[{type:'camera',name:'camera'},{type:'mesh',geometry:'surface',instances:instances.instances}]});+ const geometry=sdk.grid('surface'), instances={+ buffers:{placements:{type:'vec3',data:[[0,0,0],[2,0,0],[4,0,0]]},live:{type:'u32',data:[2]}},+ instances:{attributes:{TRANSLATION:'placements'},count:'live'},+ };+ fixtures.push({version:2,...geometry,programs:{live:{schedule:'install',dispatch:1,bindings:{live:'live'},source:'import vork; struct Inputs {} void compute(ComputeContext ctx, Inputs inputs) { live_store(0, 2u); }'}},buffers:{...geometry.buffers,...instances.buffers},nodes:[{type:'camera',name:'camera'},{type:'mesh',geometry:'surface',instances:instances.instances}]});const previousBinary=process.env.VORK_BIN;process.env.VORK_BIN=previousBinary ?? resolve(root,process.env.CARGO_TARGET_DIR ?? 'target','release','vork');const font = join(root,'crates/vork-std/tests/fonts/LiberationSans-Regular.ttf');diff --git a/packages/ts/test/options.test.mjs b/packages/ts/test/options.test.mjsindex bd00c9f..82fa529 100644--- a/packages/ts/test/options.test.mjs+++ b/packages/ts/test/options.test.mjs@@ -11,8 +11,8 @@ test('shape options suggest names and reject the misspelling', () => {assert.throws(() => sdk.extrude('plate',{outline:[],depht:2}), /did you mean "depth"/);});-test('render and renderArguments diagnose options before invoking the CLI', () => {- for (const render of [sdk.render, sdk.renderArguments]) {+test('render diagnoses options before invoking the CLI', () => {+ for (const render of [sdk.render]) {assert.throws(() => render('missing.json',{out:'out.png',proflie:[10,10]}), /unknown option "proflie"; did you mean "profile"\? Nearest valid names/);assert.throws(() => render('missing.json',{out:'out.png',zzzzzzzz:1}), error => /Nearest valid names/.test(error.message) && !error.message.includes('did you mean'));}diff --git a/packages/ts/test/render.test.mjs b/packages/ts/test/render.test.mjsindex 00b9f71..94635c9 100644--- a/packages/ts/test/render.test.mjs+++ b/packages/ts/test/render.test.mjs@@ -5,17 +5,18 @@ import {tmpdir} from 'node:os';import {join, dirname} from 'node:path';import {execFileSync} from 'node:child_process';-test('render prints exposure and returns precise per-output summaries', async () => {+for (const hasWarnings of [true, false]) test(`render preserves exposure with ${hasWarnings ? '0.2' : '0.1'} metadata`, async () => {const directory=await mkdtemp(join(tmpdir(),'vork-sdk-report-'));const summary={frames:2,coverage:0.5,clipped:0.123456789,near_black:0.2,mean:0.41,worst_clipped:{share:0.25,frame:7},worst_near_black:{share:0.3,frame:8}};const empty={frames:1,coverage:0,clipped:null,near_black:null,mean:null,worst_clipped:null,worst_near_black:null};const summaries=[summary,empty,summary];+ const warning={code:"additional_environment",requested:{node:{name:"second",energy:2}},dropped:"second environment; retaining first"};try {const outputs=['still.png','clip.MOV','frames.png/','controls','exr/%06d.exr'].map(p=>directory+'/'+p);const metas=['still.png.meta.json','clip.MOV.meta.json','frames.png/meta.json','controls/meta.json','exr/meta.json'];for(let i=0;i<metas.length;i++) {const path=join(directory,metas[i]);await mkdir(dirname(path),{recursive:true});- await writeFile(path,JSON.stringify(i<3?{exposure:summaries[i]}:{}));+ await writeFile(path,JSON.stringify({...(i<3?{exposure:summaries[i]}:{}), ...(hasWarnings?{warnings:[warning]}:{})}));}const executable=join(directory,'vork');await writeFile(executable,'#!/usr/bin/env node\nconsole.log("exposure: 12% clipped, 20% near-black, mean 0.41");\n',{mode:0o700});@@ -23,6 +24,6 @@ test('render prints exposure and returns precise per-output summaries', async ()const source=`import {render} from ${JSON.stringify(module)}; console.log(JSON.stringify(render('shot.json',{out:${JSON.stringify(outputs)}})));`;const output=execFileSync(process.execPath,['--input-type=module','-e',source],{env:{...process.env,VORK_BIN:executable},encoding:'utf8'});assert.match(output,/exposure: 12% clipped/);- assert.deepEqual(JSON.parse(output.trim().split('\n').at(-1)),{exposure:outputs.slice(0,3).map((output,i)=>({output,exposure:summaries[i]}))});+ assert.deepEqual(JSON.parse(output.trim().split('\n').at(-1)),{exposure:outputs.slice(0,3).map((output,i)=>({output,exposure:summaries[i]})),warnings:hasWarnings?[warning]:[]});} finally {await rm(directory,{recursive:true,force:true});}});diff --git a/packages/ts/test/resource-slots.test.mjs b/packages/ts/test/resource-slots.test.mjsnew file mode 100644index 0000000..8a883bc--- /dev/null+++ b/packages/ts/test/resource-slots.test.mjs@@ -0,0 +1,27 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import { mkdtemp, mkdir, writeFile, readFile, rm, realpath } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { writeScene } from '../dist/index.js';++test('every schema resource slot preserves identity, including recursive and opaque names', async () => {+ const cases = JSON.parse(execFileSync(process.platform === 'win32' ? 'python' : 'python3', ['../python/test_resource_slots.py'], {encoding: 'utf8'}));+ assert.ok(cases.length > 100);+ const root = await mkdtemp(join(tmpdir(), 'vork-resource-slots-'));+ try {+ const source = join(root, 'source');+ await mkdir(source);+ await writeFile(join(source, 'resource.bin'), 'resource');+ for (const {path, scene} of cases) {+ const original = structuredClone(scene);+ const output = join(root, 'export', 'scene.json');+ await writeScene(scene, output, source);+ const saved = JSON.parse(await readFile(output, 'utf8'));+ const file = path.reduce((value, key) => value[key], saved);+ assert.equal(await realpath(resolve(root, 'export', file)), await realpath(join(source, 'resource.bin')), path.join('.'));+ assert.deepEqual(scene, original);+ }+ } finally { await rm(root, {recursive: true, force: true}); }+});diff --git a/packages/ts/test/scatter.test.mjs b/packages/ts/test/scatter.test.mjsdeleted file mode 100644index 0adc39c..0000000--- a/packages/ts/test/scatter.test.mjs+++ /dev/null@@ -1,55 +0,0 @@-import test from 'node:test';-import assert from 'node:assert/strict';-import {scatter, grid} from '../dist/index.js';-import {readFileSync} from 'node:fs';-import {runInNewContext} from 'node:vm';-const transforms = result => {- const {TRANSLATION,ROTATION}=result.instances.attributes;- return result.buffers[TRANSLATION].data.map((p,i)=>{- const [x,y,z,w]=result.buffers[ROTATION].data[i];- return [1-2*(y*y+z*z),2*(x*y+w*z),2*(x*z-w*y),0,- 2*(x*y-w*z),1-2*(x*x+z*z),2*(y*z+w*x),0,- 2*(x*z+w*y),2*(y*z-w*x),1-2*(x*x+y*y),0,...p,1];- });-};-test('scatter is seeded, samples surface area and aligns +Y to the face normal',()=>{- const source={buffers:{p:{type:'vec3',data:[[0,0,0],[2,0,0],[0,0,1],[10,0,0],[16,0,0],[10,0,1]]}},geometry:{surface:{attributes:{POSITION:'p'}}}};- const rows=transforms(scatter(source,1000,42));- assert.deepEqual(rows,transforms(scatter(source,1000,42)));- assert.notDeepEqual(rows,transforms(scatter(source,1000,43)));- const larger=rows.filter(x=>x[12]>=10).length;- assert.ok(larger>680&&larger<820,`area ratio 3:1: ${larger}`);- for(const m of rows){- assert.ok(m.every(Number.isFinite));assert.ok(m.slice(4,7).every((v,i)=>Math.abs(v-[0,-1,0][i])<1e-12));- assert.equal(m[13],0);assert.ok(m[14]>=0&&m[14]<=1);- const x=m[12]<10?m[12]/2:(m[12]-10)/6;assert.ok(x+m[14]<=1+1e-12);- }-});-test('scatter rejects unreadable, degenerate and invalid geometry',()=>{- assert.throws(()=>scatter(grid('p'),1,-1),/uint32/);- assert.throws(()=>scatter(grid('p'),0,1),/positive/);- const source=grid('p');source.buffers.p_position={type:'vec3',file:'positions.bin'};- assert.throws(()=>scatter(source,1,1),/inline/);- const invalid=grid('p');invalid.buffers.p_indices.data=[999,1,2];assert.throws(()=>scatter(invalid,1,1),/valid vertex/);- const zero=grid('p');zero.buffers.p_position.data.fill([0,0,0]);assert.throws(()=>scatter(zero,1,1),/nonzero/);-});--test('generated CLI std dispatch reaches surface sampling',()=>{- const script=readFileSync(new URL('../../../crates/vork-std/src/sdk.js',import.meta.url),'utf8');- const evaluate=(name,args)=>JSON.parse(runInNewContext(script+'; JSON.stringify(stdEvaluate(name,args))',{name,args,structuredClone}));- const source=grid('surface');- assert.deepEqual(evaluate('scatter',{on_geometry:source,count:3,seed:8}),JSON.parse(JSON.stringify(scatter(source,3,8))));- assert.ok(transforms(scatter(source,1,0)).length===1);- const sides=Array.from({length:10},(_,seed)=>transforms(scatter(source,1,seed))[0][12]);- assert.ok(Math.max(...sides)-Math.min(...sides)>0.5,'adjacent seeds spread the first sample');- const other=grid('other');assert.notEqual(scatter(source,1,0).instances.attributes.TRANSLATION,scatter(other,1,0).instances.attributes.TRANSLATION);-});--test('scatter accepts inline position and index buffers',()=>{- const source=grid('p');- const expected=scatter(source,8,42);- const geometry=source.geometry.p;- geometry.attributes.POSITION=source.buffers[geometry.attributes.POSITION];- geometry.indices=source.buffers[geometry.indices];- assert.deepEqual(scatter(source,8,42),expected);-});diff --git a/packages/ts/test/serialization.test.mjs b/packages/ts/test/serialization.test.mjsindex 981fe2e..b980d0c 100644--- a/packages/ts/test/serialization.test.mjs+++ b/packages/ts/test/serialization.test.mjs@@ -6,6 +6,29 @@ import { mkdtemp, readFile, rm, rename, mkdir, writeFile, symlink, realpath, chmimport { tmpdir } from 'node:os';import { dirname, join, resolve } from 'node:path';import * as sdk from '../dist/index.js';+import {mkdtempSync, writeFileSync, readFileSync, rmSync} from 'node:fs';+// Exercise argv through the public render wrapper and a child process.+function renderArguments(scene, options) {+ const dir = mkdtempSync(join(tmpdir(), 'vork-render-argv-'));+ const binary = join(dir, 'vork');+ const capture = join(dir, 'argv.json');+ const previous = process.env.VORK_BIN;+ writeFileSync(binary, '#!/usr/bin/env node\n' ++ `require('node:fs').writeFileSync(${JSON.stringify(capture)}, JSON.stringify(process.argv.slice(2)));`, {mode:0o755});+ process.env.VORK_BIN = binary;+ try {+ // The child only captures arguments; reading absent exposure metadata then fails.+ try { sdk.render(scene, options); } catch (error) { if (error.code !== 'ENOENT') throw error; }+ return JSON.parse(readFileSync(capture, 'utf8'));+ } finally {+ if (previous === undefined) delete process.env.VORK_BIN; else process.env.VORK_BIN = previous;+ rmSync(dir, {recursive:true,force:true});+ }+}++test('argv builders are absent from the public SDK', () => {+ assert.equal('renderArguments' in sdk, false);+});test('SDK resolves resource paths without mutating its input', async () => {const directory = await mkdtemp(join(tmpdir(), 'vork-sdk-'));@@ -15,6 +38,11 @@ test('SDK resolves resource paths without mutating its input', async () => {try {const path = await sdk.writeScene(scene, join(directory, 'scenes/shot.json'), directory);const saved = JSON.parse(await readFile(path, 'utf8'));+ assert.equal(saved.$schema, undefined);+ assert.equal(scene.$schema, undefined);+ const annotated = {...scene, $schema: 'https://voyager.so/vork/schema/scene.schema.json'};+ const annotatedPath = await sdk.writeScene(annotated, join(directory, 'annotated.json'), directory);+ assert.equal(JSON.parse(await readFile(annotatedPath, 'utf8')).$schema, annotated.$schema);assert.equal(saved.nodes[0].children[0].file, '../model.glb');assert.equal(saved.images.sky.file, '../studio.hdr');assert.deepEqual(saved.animation, scene.animation);@@ -177,20 +205,20 @@ test('SDK preserves the containing directory of symlinked resource files', async});test('SDK render options map to vork render flags', () => {- assert.deepEqual(sdk.renderArguments('shot.json', {out: 'a.png'}), ['render', 'shot.json', '--out', 'a.png']);- assert.deepEqual(sdk.renderArguments('shot.json', {out: 'a.png', channels: ['all']}), ['render', 'shot.json', '--out', 'a.png', '--channels', 'all']);- assert.deepEqual(sdk.renderArguments('shot.json', {out: 'a.png', at: 0, set: {'resolution': [64, 32]}}),+ assert.deepEqual(renderArguments('shot.json', {out: 'a.png'}), ['render', 'shot.json', '--out', 'a.png']);+ assert.deepEqual(renderArguments('shot.json', {out: 'a.png', channels: ['all']}), ['render', 'shot.json', '--out', 'a.png', '--channels', 'all']);+ assert.deepEqual(renderArguments('shot.json', {out: 'a.png', at: 0, set: {'resolution': [64, 32]}}),['render', 'shot.json', '--out', 'a.png', '--at', '0', '--set', 'resolution=[64,32]']);- for (const key of ['resolution','samples','previs']) assert.throws(() => sdk.renderArguments('shot.json', {out:'a.png', [key]:1}), /unknown option/);- assert.deepEqual(sdk.renderArguments('shot.json', {out: 'a.png', set: {samples: 7}}),+ for (const key of ['resolution','samples','previs']) assert.throws(() => renderArguments('shot.json', {out:'a.png', [key]:1}), /unknown option/);+ assert.deepEqual(renderArguments('shot.json', {out: 'a.png', set: {samples: 7}}),['render', 'shot.json', '--out', 'a.png', '--set', 'samples=7']);- assert.ok(!sdk.renderArguments('shot.json', {out: ['a.mp4', 'b']}).includes('--previs'));- assert.deepEqual(sdk.renderArguments('shot.json', {out: 'a.png', profile: 'std/draft', set: {seed: 4}}),+ assert.ok(!renderArguments('shot.json', {out: ['a.mp4', 'b']}).includes('--previs'));+ assert.deepEqual(renderArguments('shot.json', {out: 'a.png', profile: 'std/draft', set: {seed: 4}}),['render', 'shot.json', '--out', 'a.png', '--profile', 'std/draft', '--set', 'seed=4']);- assert.deepEqual(sdk.renderArguments('shot.json', {out: 'frames/', frameStart: 3, frameEnd: 7}),+ assert.deepEqual(renderArguments('shot.json', {out: 'frames/', frameStart: 3, frameEnd: 7}),['render', 'shot.json', '--out', 'frames/', '--frame-start', '3', '--frame-end', '7']);for (const key of ['render.camera','camera','render.background','render.resolution','settings.seed','exposure']) {- assert.throws(() => sdk.renderArguments('shot.json', {out:'a.png', set:{[key]:1}}), /unknown option/);+ assert.throws(() => renderArguments('shot.json', {out:'a.png', set:{[key]:1}}), /unknown option/);}assert.throws(() => sdk.render('shot.json', {out: 'a.png', preview: true}));});@@ -350,7 +378,7 @@ test('relocation preserves expanded text geometry and nested display images', {sconst text = sdk.text('label',options);const display = {program:'blender/filmic',inputs:{lut:{image:{file:'lut.exr'}}}};const scene = {version:2,...text,nodes:[{type:'mesh',geometry:{...text.geometry.label}}],- render:{display},images:{capture:{render:{compositor:[{program:'post/glare',+ render:{display},images:{capture:{render:{compositor:[{program:'post/white_balance',inputs:{texture:{image:{file:'nested.exr'}}}}]}}}};try {const path = await sdk.writeScene(scene,join(directory,'out/scene.json'),directory);@@ -384,5 +412,5 @@ test('numeric program and material tracks preserve the shared scene IR', async (test('frame selection uses flags, never --set keys', () => {for (const key of ['frame_start','frame_end'])- assert.throws(() => sdk.renderArguments('shot.json', {out:'a.png', set:{[key]:1}}), /unknown option/);+ assert.throws(() => renderArguments('shot.json', {out:'a.png', set:{[key]:1}}), /unknown option/);});diff --git a/scripts/check-registry-bytes b/scripts/check-registry-bytesnew file mode 100755index 0000000..12b7963--- /dev/null+++ b/scripts/check-registry-bytes@@ -0,0 +1,34 @@+#!/usr/bin/env python3+"""Check that both native registry artifacts preserve every runtime file byte."""+import argparse+import hashlib+from pathlib import Path+import tarfile+import zipfile++p = argparse.ArgumentParser(description=__doc__)+p.add_argument('--tree', required=True, type=Path)+p.add_argument('--dist', required=True, type=Path)+p.add_argument('--platform', required=True)+a = p.parse_args()+expected = {}+for f in a.tree.rglob('*'):+ rel = f.relative_to(a.tree)+ if f.is_file() and rel.parts[0] not in ('sdk', 'python', 'examples', 'README.md'):+ expected[rel.as_posix()] = hashlib.sha256(f.read_bytes()).hexdigest()+with tarfile.open(next(a.dist.glob(f'voyager-so-vork-{a.platform}-*.tgz'))) as t:+ actual = {f.name.removeprefix('package/runtime/'): hashlib.sha256(t.extractfile(f).read()).hexdigest()+ for f in t if f.isfile() and f.name.startswith('package/runtime/')}+ if a.platform != 'windows-x64':+ for name in ['vork', 'slang/bin/slangc']:+ assert t.getmember('package/runtime/' + name).mode & 0o111, name+assert actual == expected, 'npm changed runtime bytes or file set'+with zipfile.ZipFile(next(a.dist.glob(f'vork_native_{a.platform.replace("-", "_")}-*.whl'))) as z:+ actual = {n.split('/runtime/', 1)[1]: hashlib.sha256(z.read(n)).hexdigest()+ for n in z.namelist() if '/runtime/' in n}+ if a.platform != 'windows-x64':+ for name in ['vork', 'slang/bin/slangc']:+ info = z.getinfo('vork_native_' + a.platform.replace('-', '_') + '/runtime/' + name)+ assert (info.external_attr >> 16) & 0o111, name+assert actual == expected, 'wheel changed runtime bytes or file set'+print(f'{a.platform}: {len(expected)} runtime files preserved byte for byte in npm and wheel')diff --git a/scripts/create-vork.cjs b/scripts/create-vork.cjsnew file mode 100755index 0000000..68950ba--- /dev/null+++ b/scripts/create-vork.cjs@@ -0,0 +1,40 @@+#!/usr/bin/env node+'use strict';+const {spawnSync} = require('node:child_process');+const fs = require('node:fs');+const path = require('node:path');+const args = process.argv.slice(2);+const metadata = require.resolve('@voyager-so/vork/package.json');+const cli = path.join(path.dirname(metadata), 'cli.cjs');+function run(command, argv, cwd, stdio = 'inherit') {+ const result = spawnSync(command, argv, {stdio, cwd});+ if (result.error) throw result.error;+ if (result.status !== 0) process.exit(result.status ?? 1);+ return result;+}+if (args.includes('--help') || args.includes('-h')) {+ run(process.execPath, [cli, 'init', '--help']);+ process.exit(0);+}+// Match init's positional directory; clap owns validation of all options.+let dir = '.';+let positional = false;+for (let i = 0; i < args.length; ++i) {+ if (positional) { dir = args[i]; continue; }+ if (args[i] === '--') { positional = true; continue; }+ if (args[i] === '--language') { ++i; continue; }+ if (!args[i].startsWith('-')) dir = args[i];+}+const project = path.resolve(dir);+if (fs.existsSync(path.join(project, 'package.json')) || fs.existsSync(path.join(project, 'node_modules'))) {+ console.error('create-vork: package.json or node_modules already exists; choose another directory.');+ process.exit(1);+}+const initialized = run(process.execPath, [cli, 'init', ...args], undefined, ['inherit', 'pipe', 'inherit']);+process.stdout.write(initialized.stdout.toString().replace(/^ vork /gm, ' npx vork '));+const version = require(metadata).version;+fs.writeFileSync(path.join(project, 'package.json'), JSON.stringify({private: true, type: 'module', dependencies: {'@voyager-so/vork': version}}, null, 2) + '\n', {flag: 'wx'});+// npm create has already cached this exact dependency and its selected native package.+// Never fetch during initialization; propagate the caller's private registry settings.+run(process.execPath, [process.env.npm_execpath, 'install', '--offline', '--ignore-scripts', '--no-audit', '--no-fund'], project);+console.log('Ready. Enter the project and run:\n npx vork render scene.json --profile std/draft --out render.png\n npx vork help');diff --git a/scripts/package-registries b/scripts/package-registriesnew file mode 100755index 0000000..db13582--- /dev/null+++ b/scripts/package-registries@@ -0,0 +1,163 @@+#!/usr/bin/env python3+"""Convert an assembled release tree to npm packages and wheels; never publishes.++Run after platform signing/notarization. No stripping, patching or repair is allowed.+"""+import argparse+import base64+import csv+import hashlib+import io+import json+from pathlib import Path+import shutil+import struct+import re+import subprocess+import tempfile+import tomllib+import zipfile++ROOT = Path(__file__).resolve().parents[1]+TARGETS = {+ 'linux-x64': ('linux', 'x64', 'manylinux_2_35_x86_64', 'sys_platform == "linux" and platform_machine == "x86_64"'),+ 'darwin-arm64': ('darwin', 'arm64', None, 'sys_platform == "darwin" and platform_machine == "arm64"'),+ 'windows-x64': ('win32', 'x64', 'win_amd64', 'sys_platform == "win32" and platform_machine == "AMD64"'),+}+++def wheel(output, name, version, tag, files, requires=(), entry=None):+ normalized = name.replace('-', '_')+ info = f'{normalized}-{version}.dist-info'+ files = dict(files)+ files[f'{info}/METADATA'] = (f'Metadata-Version: 2.4\nName: {name}\nVersion: {version}\nRequires-Python: >=3.11\nLicense-Expression: LicenseRef-vork-Preview\nLicense-File: LICENSE\nDescription-Content-Type: text/plain\n' + ''.join(f'Requires-Dist: {r}\n' for r in requires) + '\nNative vork engine and SDK distribution. See https://github.com/voyager-so/vork for usage and licence terms.\n').encode()+ files[f'{info}/licenses/LICENSE'] = (ROOT / 'LICENSE').read_bytes()+ files[f'{info}/WHEEL'] = f'Wheel-Version: 1.0\nGenerator: vork\nRoot-Is-Purelib: {str(tag == "any").lower()}\nTag: py3-none-{tag}\n'.encode()+ if entry:+ files[f'{info}/entry_points.txt'] = b'[console_scripts]\nvork = vork._engine:main\n'+ records = []+ path = output / f'{normalized}-{version}-py3-none-{tag}.whl'+ with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as archive:+ for name, source in sorted(files.items()):+ data = source.read_bytes() if isinstance(source, Path) else source+ item = zipfile.ZipInfo(name)+ item.compress_type = zipfile.ZIP_DEFLATED+ mode = (source.stat().st_mode & 0o777) if isinstance(source, Path) else 0o644+ item.external_attr = (0o100000 | mode) << 16+ archive.writestr(item, data)+ digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b'=').decode()+ records.append((name, 'sha256=' + digest, len(data)))+ record = io.StringIO(newline='')+ writer = csv.writer(record)+ writer.writerows(records + [(f'{info}/RECORD', '', '')])+ archive.writestr(f'{info}/RECORD', record.getvalue())+ print(f'{path}: {path.stat().st_size} bytes')+++def main():+ p = argparse.ArgumentParser(description=__doc__)+ p.add_argument('--tree', type=Path, required=True, help='extracted complete, signed release archive')+ p.add_argument('--platform', choices=TARGETS, required=True)+ p.add_argument('--output', type=Path, required=True)+ a = p.parse_args()+ version = tomllib.loads((ROOT / 'Cargo.toml').read_text())['workspace']['package']['version']+ if '-' in version:+ p.error('registry candidate must use a final numeric version; private registries isolate rehearsals')+ tree = a.tree.resolve()+ binary = 'vork.exe' if a.platform == 'windows-x64' else 'vork'+ for name in [binary, 'slang', 'oidn', 'shaders', 'LICENSE', 'NOTICE', 'licenses', 'libraries', 'sdk', 'python']:+ if not (tree / name).exists():+ p.error(f'incomplete release tree: missing {name}')+ if json.loads((tree / 'sdk/package.json').read_text())['version'] != version:+ p.error('release SDK version does not match Cargo version')+ header = (tree / binary).read_bytes()+ if a.platform == 'linux-x64' and not (header[:5] == b'\x7fELF\x02' and struct.unpack_from('<H', header, 18)[0] == 62):+ p.error('expected an x86-64 ELF engine')+ if a.platform == 'darwin-arm64' and not (header[:4] == b'\xcf\xfa\xed\xfe' and struct.unpack_from('<I', header, 4)[0] == 0x100000c):+ p.error('expected an arm64 Mach-O engine')+ if a.platform == 'windows-x64':+ pe = struct.unpack_from('<I', header, 0x3c)[0]+ if header[:2] != b'MZ' or header[pe:pe+6] != b'PE\0\0\x64\x86':+ p.error('expected an x86-64 PE engine')+ a.output.mkdir(parents=True, exist_ok=True)+ # npm drops symlinks. Materialize internal links with identical target bytes;+ # wheels do the same. Never follow a link outside the signed runtime tree.+ runtime = {}+ for f in sorted(tree.rglob('*')):+ rel = f.relative_to(tree)+ if rel.parts[0] in ('sdk', 'python', 'examples', 'README.md'):+ continue+ if rel.parts[0] not in (binary, 'slang', 'oidn', 'shaders', 'LICENSE', 'NOTICE', 'licenses', 'libraries'):+ p.error(f'unexpected release content: {rel}')+ if not f.resolve().is_relative_to(tree):+ p.error(f'runtime symlink escapes tree: {rel}')+ if f.is_symlink() and not f.is_file():+ p.error(f'runtime link must target a regular file: {rel}')+ if f.is_file():+ runtime[rel.as_posix()] = f+ os_name, cpu, tag, _ = TARGETS[a.platform]+ if a.platform == 'darwin-arm64':+ minimum = (11, 0)+ for source in runtime.values():+ data = source.read_bytes()+ if data[:4] != b'\xcf\xfa\xed\xfe':+ continue+ offset = 32+ for _ in range(struct.unpack_from('<I', data, 16)[0]):+ command, size = struct.unpack_from('<II', data, offset)+ if command in (0x32, 0x24): # LC_BUILD_VERSION / LC_VERSION_MIN_MACOSX+ value = struct.unpack_from('<I', data, offset + (12 if command == 0x32 else 8))[0]+ minimum = max(minimum, (value >> 16, (value >> 8) & 255))+ if size < 8:+ p.error(f'invalid Mach-O load command: {source}')+ offset += size+ tag = f'macosx_{minimum[0]}_{minimum[1]}_arm64'+ if a.platform == 'linux-x64':+ for source in runtime.values():+ data = source.read_bytes()+ if data[:4] == b'\x7fELF':+ versions = [tuple(map(int, v)) for v in re.findall(rb'GLIBC_(\d+)\.(\d+)', data)]+ if versions and max(versions) > (2, 35):+ p.error(f'{source} exceeds the glibc 2.35 baseline: {max(versions)}')+ with tempfile.TemporaryDirectory() as tmp:+ stage = Path(tmp)+ native = stage / 'native'+ native.mkdir()+ for name, source in runtime.items():+ dest = native / 'runtime' / name+ dest.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(source, dest)+ native_meta = dict(name=f'@voyager-so/vork-{a.platform}', version=version, os=[os_name], cpu=[cpu], license='SEE LICENSE IN runtime/LICENSE')+ if a.platform == 'linux-x64':+ native_meta['libc'] = ['glibc']+ (native / 'package.json').write_text(json.dumps(native_meta))+ subprocess.run([shutil.which('npm'), 'pack', '--ignore-scripts', '--pack-destination', str(a.output.resolve())], cwd=native, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ main = stage / 'main'+ shutil.copytree(ROOT / 'packages/ts/dist', main / 'dist')+ shutil.copy2(ROOT / 'packages/ts/scene.schema.json', main / 'scene.schema.json')+ shutil.copy2(ROOT / 'LICENSE', main / 'LICENSE')+ shutil.copy2(ROOT / 'scripts/registry-cli.cjs', main / 'cli.cjs')+ meta = json.loads((ROOT / 'packages/ts/package.json').read_text())+ for key in ('scripts', 'devDependencies'):+ meta.pop(key, None)+ (main / 'README.md').write_text('# vork\n\nNative renderer and TypeScript SDK. Install with `npm install @voyager-so/vork`, then run `npx vork init my-shot`. Enter my-shot and run `npx vork render scene.json --profile std/draft --out render.png`, then `npx vork help`. Use `npm create vork my-shot` for project-local engine installation. Run `npx vork setup` explicitly after upgrades or driver changes; setup can take minutes and prints progress. Import the SDK from `@voyager-so/vork`. Keep optional dependencies enabled; reinstall dependencies on each machine. Requires Node 22.18+, a supported GPU and its drivers; Linux/Windows video also needs ffmpeg. See https://github.com/voyager-so/vork for platform requirements and examples.\n')+ meta.update(description='Native vork renderer, TypeScript SDK and scene schema', version=version, bin={'vork': 'cli.cjs'}, files=['dist', 'cli.cjs', 'LICENSE', 'README.md', 'scene.schema.json'], optionalDependencies={f'@voyager-so/vork-{t}': version for t in TARGETS})+ meta['exports']['./package.json'] = './package.json'+ (main / 'package.json').write_text(json.dumps(meta, indent=2) + '\n')+ subprocess.run([shutil.which('npm'), 'pack', '--ignore-scripts', '--pack-destination', str(a.output.resolve())], cwd=main, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ creator = stage / 'creator'+ creator.mkdir()+ shutil.copy2(ROOT / 'scripts/create-vork.cjs', creator / 'cli.cjs')+ shutil.copy2(ROOT / 'LICENSE', creator / 'LICENSE')+ (creator / 'package.json').write_text(json.dumps(dict(name='create-vork', version=version, description='Create an offline vork rendering project', bin={'create-vork': 'cli.cjs'}, engines={'node': '>=22.18'}, license='SEE LICENSE IN LICENSE', dependencies={'@voyager-so/vork': version}), indent=2) + '\n')+ subprocess.run([shutil.which('npm'), 'pack', '--ignore-scripts', '--pack-destination', str(a.output.resolve())], cwd=creator, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ module = 'vork_native_' + a.platform.replace('-', '_')+ wheel(a.output, 'vork-native-' + a.platform, version, tag,+ {f'{module}/__init__.py': b''} | {f'{module}/runtime/{n}': f for n, f in runtime.items()})+ python = {f'vork/{f.relative_to(ROOT / "packages/python/vork").as_posix()}': f for f in (ROOT / 'packages/python/vork').rglob('*') if f.is_file() and '__pycache__' not in f.parts}+ requires = [f'vork-native-{t}=={version}; {data[3]}' for t, data in TARGETS.items()]+ wheel(a.output, 'vork', version, 'any', python, requires, entry=True)+++if __name__ == '__main__':+ main()diff --git a/scripts/package-release b/scripts/package-releaseindex f7bff30..042373a 100755--- a/scripts/package-release+++ b/scripts/package-release@@ -23,6 +23,7 @@ p.add_argument('--slang-toolchain', type=Path, required=True, help='Pinned Slangp.add_argument('--oidn-toolchain', type=Path, required=True, help='Pinned OIDN distribution from scripts/install-oidn; its runtime libraries and notices ship')p.add_argument('--msvc-runtime', type=Path, help='windows-x64: Visual Studio redist folder (VC\\Redist\\MSVC\\<version>\\x64\\Microsoft.VC14x.CRT); the VC++ runtime DLLs that shipped DLLs import are copied beside them')a = p.parse_args()+subprocess.run([sys.executable, str(ROOT / 'scripts/sync-version'), '--check'], check=True)cargo_version = tomllib.loads((ROOT / 'Cargo.toml').read_text())['workspace']['package']['version']try:reported = subprocess.check_output([str(a.binary.resolve()), '--version'], text=True).split()@@ -159,7 +160,19 @@ with tempfile.TemporaryDirectory(dir=a.output) as tmp:for f in ['LICENSE', 'NOTICE', 'README.md']:shutil.copy2(ROOT / f, stage / f)shutil.copytree(ROOT / 'dist/licenses', stage / 'licenses')- shutil.copytree(ROOT / 'examples', stage / 'examples')+ # Match the public source payload, never sweep the private checkout or downloads.+ for relative in (ROOT / 'dist/example-payload.txt').read_text().splitlines():+ if not relative or relative.startswith('#'):+ continue+ path = Path(relative)+ if path.is_absolute() or '..' in path.parts or path.parts[0] != 'examples':+ p.error(f'invalid example payload path: {relative}')+ source = ROOT / path+ if source.is_symlink() or not source.is_file():+ p.error(f'missing or symlink example payload input: {relative}')+ target = stage / path+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(source, target)copy_selected(ROOT, stage, ['libraries/blender/filmic.exr'])sdk = ROOT / 'packages/ts'if not (sdk / 'dist/index.js').exists():@@ -168,10 +181,16 @@ with tempfile.TemporaryDirectory(dir=a.output) as tmp:shutil.copy2(sdk / 'scene.schema.json', stage / 'sdk/scene.schema.json')shutil.copy2(ROOT / 'LICENSE', stage / 'sdk/LICENSE')metadata = json.loads((sdk / 'package.json').read_text(encoding='utf-8'))- (stage / 'sdk/package.json').write_text(json.dumps({- 'name': metadata['name'], 'version': metadata['version'], 'type': 'module',- 'license': metadata['license']- }, indent=2) + '\n', encoding='utf-8')+ # Archives flatten dist/ into sdk/; keep the canonical public entry points.+ def archive_exports(value):+ if isinstance(value, dict):+ return {key: archive_exports(entry) for key, entry in value.items()}+ if isinstance(value, list):+ return [archive_exports(entry) for entry in value]+ return './' + value[len('./dist/'):] if isinstance(value, str) and value.startswith('./dist/') else value+ archive_metadata = {key: metadata[key] for key in ('name', 'version', 'type', 'license', 'engines')}+ archive_metadata['exports'] = archive_exports(metadata['exports'])+ (stage / 'sdk/package.json').write_text(json.dumps(archive_metadata, indent=2) + '\n', encoding='utf-8')# Python SDK: a pip-installable source tree (pip install PREFIX/lib/vork/python).shutil.copytree(ROOT / 'packages/python', stage / 'python',ignore=shutil.ignore_patterns('generate.py', 'test_*.py', '__pycache__', '*.egg-info', 'build'))diff --git a/scripts/registry-cli.cjs b/scripts/registry-cli.cjsnew file mode 100755index 0000000..2e7fe0b--- /dev/null+++ b/scripts/registry-cli.cjs@@ -0,0 +1,35 @@+#!/usr/bin/env node+'use strict';+const {spawn} = require('node:child_process');+const target = `${process.platform === 'win32' ? 'windows' : process.platform}-${process.arch}`;+if (!['linux-x64', 'darwin-arm64', 'windows-x64'].includes(target)) {+ console.error(`vork: unsupported platform ${target}`);+ process.exit(1);+}+let binary;+try {+ binary = require.resolve(`@voyager-so/vork-${target}/runtime/${process.platform === 'win32' ? 'vork.exe' : 'vork'}`);+} catch {+ console.error('vork: native package missing. Reinstall @voyager-so/vork with optional dependencies enabled (--include=optional).');+ process.exit(1);+}+const args = process.argv.slice(2);+if (['setup', 'render'].includes(args[0])) {+ console.error('vork: GPU shader compilation can take several minutes on first use. Run `vork setup` after upgrading or changing drivers.');+}+const child = spawn(binary, args, {stdio: 'inherit'});+const timer = args[0] === 'setup' ? setInterval(() => console.error('vork: setup is still compiling GPU shaders…'), 15000) : null;+for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));+child.on('error', error => {+ if (timer) clearInterval(timer);+ console.error(`vork: ${error.message}`);+ process.exitCode = 1;+});+child.on('exit', (code, signal) => {+ if (timer) clearInterval(timer);+ if (signal) {+ for (const forwarded of ['SIGINT', 'SIGTERM']) process.removeAllListeners(forwarded);+ process.kill(process.pid, signal);+ }+ else process.exitCode = code ?? 1;+});diff --git a/scripts/rehearse-registries b/scripts/rehearse-registriesnew file mode 100755index 0000000..1bcaeac--- /dev/null+++ b/scripts/rehearse-registries@@ -0,0 +1,128 @@+#!/usr/bin/env python3+"""Publish ONLY to a fresh loopback Verdaccio and serve a local Python index.+Needs Node >=22.18, npm, Python >=3.11 (venv/pip). No real-registry writes.+"""+import argparse+import functools+import http.server+import json+import os+from pathlib import Path+import platform+import shutil+import socket+import subprocess+import sys+import threading+import time+import urllib.request++ROOT = Path(__file__).resolve().parents[1]+p = argparse.ArgumentParser(description=__doc__)+p.add_argument('--dist', type=Path, required=True)+p.add_argument('--work', type=Path, required=True, help='new directory outside the repository')+p.add_argument('--gpu', action='store_true')+p.add_argument('--init', action='store_true', help='also test project creation; needs native archives containing vork init')+a = p.parse_args()+a.dist = a.dist.resolve()+a.work = a.work.resolve()+a.work.mkdir(parents=True, exist_ok=False)+target = {('Linux', 'x86_64'): 'linux-x64', ('Darwin', 'arm64'): 'darwin-arm64', ('Windows', 'AMD64'): 'windows-x64'}[(platform.system(), platform.machine())]+npm = shutil.which('npm')+env = os.environ.copy()+env.pop('VORK_BIN', None)+env['npm_config_cache'] = str(a.work / 'npm-cache')++def run(command, cwd=a.work):+ print('+', *map(str, command), flush=True)+ subprocess.run(list(map(str, command)), cwd=cwd, env=env, check=True)++# Download the test server from npm; never upload to its upstream registry.+run([npm, 'install', '--prefix', a.work / 'tools', '--registry', 'https://registry.npmjs.org', '[email protected]'])+with socket.socket() as sock:+ sock.bind(('127.0.0.1', 0))+ port = sock.getsockname()[1]+url = f'http://127.0.0.1:{port}'+registry = ['--registry', url, f'--@voyager-so:registry={url}']+config = a.work / 'verdaccio.yaml'+# JSON is YAML, including properly quoted Windows paths.+config.write_text(json.dumps({'storage': str(a.work / 'storage'), 'max_body_size': '300mb',+ 'auth': {'htpasswd': {'file': str(a.work / 'htpasswd')}}, 'uplinks': {},+ 'packages': {'@voyager-so/*': {'access': '$all', 'publish': '$all'}, 'create-vork': {'access': '$all', 'publish': '$all'}},+ 'log': {'type': 'stdout', 'format': 'pretty', 'level': 'warn'}}))+server_log = (a.work / 'verdaccio.log').open('w')+server = subprocess.Popen([shutil.which('node'), str(a.work / 'tools/node_modules/verdaccio/bin/verdaccio'), '--config', str(config), '--listen', f'127.0.0.1:{port}'], stdout=server_log, stderr=subprocess.STDOUT, env=env)+index = a.work / 'index'+index.mkdir()+# A PEP 503 simple index; only our freshly generated artifacts are visible.+for wheel in a.dist.glob('*.whl'):+ name = wheel.name.split('-')[0].replace('_', '-')+ project = index / 'simple' / name+ project.mkdir(parents=True, exist_ok=True)+ shutil.copy2(wheel, index / wheel.name)+ (project / 'index.html').write_text(f'<a href="../../{wheel.name}">{wheel.name}</a>\n')+handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(index))+http = http.server.ThreadingHTTPServer(('127.0.0.1', 0), handler)+threading.Thread(target=http.serve_forever, daemon=True).start()+try:+ for _ in range(100):+ try:+ urllib.request.urlopen(url + '/-/ping', timeout=1).close()+ break+ except OSError:+ if server.poll() is not None:+ raise RuntimeError('Verdaccio exited; see verdaccio.log')+ time.sleep(.1)+ else:+ raise RuntimeError('Verdaccio did not start')+ auth = f'--//127.0.0.1:{port}/:_authToken=private-test'+ patterns = [f'voyager-so-vork-{t}-*.tgz' for t in ['linux-x64', 'darwin-arm64', 'windows-x64'] if list(a.dist.glob(f'voyager-so-vork-{t}-*.tgz'))]+ if f'voyager-so-vork-{target}-*.tgz' not in patterns:+ raise RuntimeError('host native artifact missing')+ for pattern in patterns + ['voyager-so-vork-[0-9]*.tgz', 'create-vork-*.tgz']:+ files = list(a.dist.glob(pattern))+ if len(files) != 1:+ raise RuntimeError(f'expected one artifact: {pattern}')+ run([npm, 'publish', files[0], *registry, '--ignore-scripts', '--access', 'public', auth])+ project = a.work / 'project'+ project.mkdir()+ if a.init:+ run([npm, 'create', 'vork', 'starter project', *registry, '--yes', '--', '--language', 'typescript'], a.work)+ run([npm, 'exec', '--offline', '--', 'vork', 'help'], a.work / 'starter project')+ run([shutil.which('node'), 'scene.ts'], a.work / 'starter project')+ run([npm, 'init', '-y'], project)+ run([npm, 'install', '@voyager-so/vork', *registry, '--ignore-scripts'], project)+ installed = sorted(p.name for p in (project / 'node_modules/@voyager-so').iterdir())+ assert installed == sorted(['vork', 'vork-' + target]), installed+ if len(patterns) == 3:+ shutil.rmtree(project / 'node_modules')+ run([npm, 'ci', *registry, '--ignore-scripts'], project)+ else:+ print('npm ci portability check needs all three native tarballs; host install only.', flush=True)+ run([sys.executable, '-m', 'venv', project / '.venv'])+ python = project / '.venv' / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')+ run([python, '-m', 'pip', 'install', '--index-url', f'http://127.0.0.1:{http.server_address[1]}/simple/', '--no-cache-dir', 'vork'], project)+ run([python, ROOT / 'scripts/test-registry-install', *(['--gpu'] if a.gpu else [])], project)+ if a.init:+ run([npm, 'exec', '--offline', '--', 'vork', 'init', 'python starter', '--language', 'python'], project)+ run([python, 'scene.py'], project / 'python starter')+ # Kill the sole npm server: prove cached project creation has no network fallback.+ server.terminate()+ server.wait(timeout=15)+ run([npm, 'create', 'vork', 'offline starter', *registry, '--offline', '--yes'], a.work)+ run([npm, 'exec', '--offline', '--', 'vork', 'help'], a.work / 'offline starter')+ if sys.platform == 'darwin':+ # Verify both package-manager extractions, including every dylib and slangc.+ for root in [project / 'node_modules/@voyager-so', project / '.venv']:+ for file in root.rglob('*'):+ if file.is_file() and 'runtime' in file.relative_to(root).parts and (file.name in ('vork', 'slangc') or file.suffix == '.dylib'):+ run(['codesign', '--verify', '--strict', '--verbose=2', file])+ identity = subprocess.run(['codesign', '-dv', '--verbose=4', str(file)], capture_output=True, text=True, check=True)+ print(identity.stderr, flush=True)+ if 'Authority=Developer ID Application:' not in identity.stderr:+ raise RuntimeError(f'not Developer ID signed: {file}')+finally:+ server.terminate()+ server.wait(timeout=15)+ server_log.close()+ http.shutdown()diff --git a/scripts/select-registry-artifact b/scripts/select-registry-artifactnew file mode 100755index 0000000..6912bdb--- /dev/null+++ b/scripts/select-registry-artifact@@ -0,0 +1,40 @@+#!/usr/bin/env python3+"""Select an unexpired private distribution artifact matching this checkout's version.+Uses read-only GitHub API calls through gh. Never changes a version or repository.+"""+import argparse+import base64+import json+import os+from pathlib import Path+import subprocess+import tomllib++p = argparse.ArgumentParser(description=__doc__)+p.add_argument('--workflow', required=True)+p.add_argument('--platform', required=True)+p.add_argument('--run')+a = p.parse_args()+repo = os.environ.get('GITHUB_REPOSITORY', 'voyager-so/vork')+version = tomllib.loads((Path(__file__).resolve().parents[1] / 'Cargo.toml').read_text())['workspace']['package']['version']++def api(path):+ return json.loads(subprocess.check_output(['gh', 'api', f'repos/{repo}/{path}'], text=True))++runs = [api(f'actions/runs/{a.run}')] if a.run else api(f'actions/workflows/{a.workflow}/runs?status=success&per_page=100')['workflow_runs']+versions = {}+for run in runs:+ if run['conclusion'] != 'success' or Path(run['path']).name != a.workflow:+ continue+ sha = run['head_sha']+ if sha not in versions:+ content = api(f'contents/Cargo.toml?ref={sha}')['content']+ versions[sha] = tomllib.loads(base64.b64decode(content).decode())['workspace']['package']['version']+ if versions[sha] != version:+ continue+ artifacts = api(f'actions/runs/{run["id"]}/artifacts?per_page=100')['artifacts']+ if any(item['name'] == a.platform and not item['expired'] for item in artifacts):+ print(run['id'])+ break+else:+ p.error(f'no successful {a.workflow} artifact for {a.platform} with source version {version}; build/sign matching artifacts or supply --run')diff --git a/scripts/shader_bundle.py b/scripts/shader_bundle.pyindex 85395d7..76defcf 100644--- a/scripts/shader_bundle.py+++ b/scripts/shader_bundle.py@@ -5,7 +5,7 @@ from pathlib import Pathimport reimport shutil-ENTRY = re.compile(r'[0-9a-f]{64}\.(?:slang-variant-v1|slang-program-v1|slang-resolve-v2|aov-resolve-v1)\.entry')+ENTRY = re.compile(r'[0-9a-f]{64}\.(?:slang-variant-v1|slang-program-v2|slang-resolve-v2|aov-resolve-v1)\.entry')def digest(path):diff --git a/scripts/sign-macos b/scripts/sign-macosindex 0c53b4b..dd4a681 100755--- a/scripts/sign-macos+++ b/scripts/sign-macos@@ -4,11 +4,11 @@ set -euo pipefailmissing=0for name in APPLE_DEVELOPER_ID_P12_BASE64 APPLE_DEVELOPER_ID_P12_PASSWORD APPLE_TEAM_ID APPLE_ID APPLE_APP_SPECIFIC_PASSWORD; doif [ -z "${!name:-}" ]; then- echo "::warning::macOS signing and notarisation skipped: $name is absent. Artifact is unsigned."+ echo "::error::macOS signing and notarisation required: $name is absent. Refusing unsigned release artifact."missing=1fidone-if [ "$missing" = 1 ]; then exit 0; fi+if [ "$missing" = 1 ]; then exit 1; fiwork=$(mktemp -d)keychain="$work/signing.keychain-db"password=$(openssl rand -hex 32)diff --git a/scripts/test-installer.py b/scripts/test-installer.pyindex e2012eb..d46b794 100644--- a/scripts/test-installer.py+++ b/scripts/test-installer.py@@ -56,6 +56,47 @@ class InstallerTests(unittest.TestCase):self.assertTrue((self.root / 'prefix/lib/vork/slang/bin/slangc').exists())self.assertTrue((self.root / 'prefix/lib/vork/oidn/lib/model').exists())+ def bundled_installer(self):+ installer = self.root / 'install.sh'+ shutil.copyfile(INSTALLER, installer)+ self.env['VORK_DOWNLOAD_BASE'] = 'file:///no-downloads-allowed'+ return subprocess.run(['sh', str(installer)], cwd='/', env=self.env,+ capture_output=True, text=True)++ def test_bundled_archive_from_another_directory(self):+ result = self.bundled_installer()+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn('Using bundled archive:', result.stdout)+ self.assertIn('fixture setup', result.stdout)++ def test_bundled_archive_requires_checksum(self):+ (self.root / 'SHA256SUMS').unlink()+ result = self.bundled_installer()+ self.assertNotEqual(result.returncode, 0)+ self.assertIn('requires SHA256SUMS', result.stderr)+ self.assertFalse((self.root / 'prefix').exists())++ def test_bundled_corruption_fails(self):+ self.archive.write_bytes(self.archive.read_bytes() + b'corruption')+ self.assertNotEqual(self.bundled_installer().returncode, 0)+ self.assertFalse((self.root / 'prefix').exists())++ def test_bundled_upgrade_replaces_tree_and_preserves_it_on_corruption(self):+ self.assertEqual(self.bundled_installer().returncode, 0)+ installed = self.root / 'prefix/lib/vork'+ stale = installed / 'dropped-by-new-release'+ stale.write_text('old')+ result = self.bundled_installer()+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertFalse(stale.exists())+ notice = (installed / 'NOTICE').read_bytes()+ self.archive.write_bytes(self.archive.read_bytes() + b'corruption')+ result = self.bundled_installer()+ self.assertNotEqual(result.returncode, 0)+ self.assertIn('Nothing was installed', result.stderr)+ self.assertEqual((installed / 'NOTICE').read_bytes(), notice)+ self.assertTrue((self.root / 'prefix/bin/vork').resolve().is_file())+def test_skip_setup(self):self.env['VORK_SKIP_SETUP'] = '1'result = self.run_installer()@@ -142,6 +183,22 @@ class InstallerTests(unittest.TestCase):self.assertIn('.local/bin', (home / '.bash_profile').read_text())self.assertFalse((home / '.profile').exists())+ @unittest.skipUnless(shutil.which('bash'), 'needs bash')+ def test_bundled_default_install_is_found_by_a_login_shell(self):+ home = self.root / 'home'; home.mkdir()+ (home / '.bashrc').write_text('[ -z "$PS1" ] && return\n')+ (home / '.profile').write_text('if [ -f ~/.bashrc ]; then . ~/.bashrc; fi\n')+ del self.env['PREFIX']+ self.env.update(SHELL='/bin/bash', PATH='/usr/bin:/bin:/usr/sbin:/sbin')+ result = self.bundled_installer()+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn('Using bundled archive:', result.stdout)+ login = subprocess.run(['bash', '-lc', 'vork --version'], cwd='/',+ env={'HOME': str(home), 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin'},+ capture_output=True, text=True)+ self.assertEqual(login.returncode, 0, login.stderr)+ self.assertIn('fixture --version', login.stdout)+def test_custom_prefix_and_opt_out_leave_startup_files_alone(self):home = self.root / 'home'; home.mkdir()self.env.update(SHELL='/bin/zsh', PATH='/usr/bin:/bin:/usr/sbin:/sbin')diff --git a/scripts/test-registry-install b/scripts/test-registry-installnew file mode 100755index 0000000..2808ca3--- /dev/null+++ b/scripts/test-registry-install@@ -0,0 +1,54 @@+#!/usr/bin/env python3+"""Check installed project packages without a global vork. Run inside a fresh+npm project and venv after installing from the private registry/index.+Rendering and setup require a supported real GPU; --gpu enables them.+"""+import argparse+import json+import ctypes+import os+import shutil+from pathlib import Path+import subprocess+import sys++p = argparse.ArgumentParser(description=__doc__)+p.add_argument('--gpu', action='store_true')+a = p.parse_args()++def run(args):+ print('+', *args, flush=True)+ args[0] = shutil.which(args[0]) or args[0]+ subprocess.run(args, check=True)++run(['npx', '--no-install', 'vork', '--version'])+run([sys.executable, '-c', 'from vork._engine import engine; import subprocess; subprocess.run([engine(), "--version"], check=True)'])+run(['node', '--input-type=module', '-e', 'import {extrude} from "@voyager-so/vork"; console.log(Object.keys(extrude("shape", {outline:[[0,0],[1,0],[0,1]]})));'])+run([sys.executable, '-c', 'from vork import std; print(list(std("sphere", name="ball")))'])+from vork._engine import engine+runtime = Path(engine()).parent+run([str(runtime / 'slang/bin' / ('slangc.exe' if os.name == 'nt' else 'slangc')), '-version'])+oidn = runtime / 'oidn' / ('bin/OpenImageDenoise.dll' if os.name == 'nt' else ('lib/libOpenImageDenoise.2.dylib' if sys.platform == 'darwin' else 'lib/libOpenImageDenoise.so.2'))+ctypes.CDLL(str(oidn))+print('Installed OIDN runtime loads:', oidn, flush=True)++if a.gpu:+ scene = {'version': 2, 'nodes': [+ {'type': 'mesh', 'geometry': 'ball', 'name': 'ball'},+ {'type': 'light', 'shape': 'point', 'translation': [2, 3, 4], 'energy': 100},+ {'type': 'camera', 'translation': [0, 0, 4], 'target': [0, 0, 0]}],+ 'render': {'resolution': [128, 128]}}+ from vork import std+ scene.update(std('sphere', name='ball'))+ Path('smoke.json').write_text(json.dumps(scene))+ for i, command in enumerate([['npx', '--no-install', 'vork'], [str(Path(sys.executable).parent / ('vork.exe' if sys.platform == 'win32' else 'vork'))]]):+ run(command + ['setup'])+ run(command + ['render', 'smoke.json', '--out', ('npm.png' if i == 0 else 'pip.png')])+ run(['node', '--input-type=module', '-e', 'import {render} from "@voyager-so/vork"; render("smoke.json", {out:"ts-api.png"});'])+ run([sys.executable, '-c', 'from vork import render; render("smoke.json", "python-api.png")'])+ run(['npx', '--no-install', 'vork', 'render', 'smoke.json', '--frame-start', '0', '--frame-end', '2', '--out', 'smoke.mp4'])+ scene['programs'] = {'paint': {'source': 'import vork; struct Inputs {}; Closure surface(ShadingContext ctx, Inputs inputs) { Closure c = {}; c.base_color = float3(0.8, 0.15, 0.05); c.specular_roughness = 0.4; return c; }'}}+ scene['materials'] = {'paint': {'program': 'paint'}}+ scene['nodes'][0]['materials'] = ['paint']+ Path('custom.json').write_text(json.dumps(scene))+ run(['npx', '--no-install', 'vork', 'render', 'custom.json', '--out', 'custom.png'])diff --git a/scripts/test_package_release.py b/scripts/test_package_release.pyindex 5ab931a..6619e40 100644--- a/scripts/test_package_release.py+++ b/scripts/test_package_release.py@@ -57,7 +57,7 @@ class PackageReleaseTests(unittest.TestCase):with tempfile.TemporaryDirectory() as tmp:root=Path(tmp); binary=root/'vork'; binary.write_bytes(b'binary')good=root/'good'; good.mkdir(); bad=root/'bad'; bad.mkdir()- name='a'*64+'.slang-program-v1.entry'+ name='a'*64+'.slang-program-v2.entry'(good/name).write_bytes(ENVELOPE); (bad/name).write_bytes(b'x'*64)for index,caches in enumerate(([good,bad],[bad,good])):output=root/str(index)@@ -116,6 +116,26 @@ class PackageReleaseTests(unittest.TestCase):archive = next((root / 'out').glob('*.tar.gz'))with tarfile.open(archive) as package:self.assertIn('vork', package.getnames())+ sdk_metadata = json.loads(package.extractfile('sdk/package.json').read())+ self.assertEqual(sdk_metadata['exports'], {+ '.': {'types': './index.d.ts', 'import': './index.js'},+ './scene.schema.json': './scene.schema.json',+ })+ self.assertEqual(sdk_metadata['engines'],+ json.loads((ROOT / 'packages/ts/package.json').read_text())['engines'])+ for path in ('sdk/index.js', 'sdk/index.d.ts', 'sdk/scene.schema.json'):+ self.assertIn(path, package.getnames())+ expected = {line for line in (ROOT / 'dist/example-payload.txt').read_text().splitlines()+ if line and not line.startswith('#')}+ actual = {entry.name for entry in package.getmembers()+ if entry.isfile() and entry.name.startswith('examples/')}+ self.assertEqual(actual, expected)+ self.assertNotIn('examples/murmuration/scene.json', actual)+ self.assertIn('examples/murmuration/launch/skim.json.in', actual)+ self.assertIn('examples/cake/scene.json.in', actual)+ for name in ('vignette.slang', 'chromatic-dispersion.slang', 'glare.slang',+ 'highlight.slang', 'glare-streaks.json'):+ self.assertIn('examples/compositor-effects/' + name, actual)for path in ('LICENSE', 'sdk/LICENSE', 'python/LICENSE'):self.assertEqual(package.extractfile(path).read(), (ROOT / 'LICENSE').read_bytes())self.assertNotIn('LICENSE-MIT', package.getnames())diff --git a/tools/gpu/Dockerfile b/tools/gpu/Dockerfilenew file mode 100644index 0000000..6227aa4--- /dev/null+++ b/tools/gpu/Dockerfile@@ -0,0 +1,23 @@+# Context: tools/gpu/prepare.py creates it from a verified Linux release archive.+# No source checkout, credentials, NVIDIA driver or GPL FFmpeg build is copied.+FROM ubuntu:24.04 AS ffmpeg+RUN apt-get update && apt-get install -y --no-install-recommends build-essential curl ca-certificates xz-utils && rm -rf /var/lib/apt/lists/*+WORKDIR /src+RUN curl -fL https://ffmpeg.org/releases/ffmpeg-7.1.3.tar.xz -o ffmpeg.tar.xz && echo 'f0bf043299db9e3caacb435a712fc541fbb07df613c4b893e8b77e67baf3adbe ffmpeg.tar.xz' | sha256sum -c - && tar xf ffmpeg.tar.xz+WORKDIR /src/ffmpeg-7.1.3+# LGPL-only, shared libraries so users can replace/relink them. H.264 encoding+# uses vork's native NVENC; this FFmpeg muxes it and supports input decoding.+RUN ./configure --prefix=/opt/ffmpeg --disable-gpl --disable-nonfree --disable-doc --disable-debug --disable-x86asm --enable-shared --disable-static && make -j4 && make install+RUN mkdir -p /opt/ffmpeg/notices && cp COPYING.LGPLv2.1 COPYING.LGPLv3 LICENSE.md /opt/ffmpeg/notices/ && cp /src/ffmpeg.tar.xz /opt/ffmpeg/notices/ && cp ffbuild/config.log /opt/ffmpeg/notices/+FROM ubuntu:24.04+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libvulkan1 libegl1 libx11-6 libxcb1 libgomp1 libstdc++6 python3 && rm -rf /var/lib/apt/lists/*+COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg+COPY bundle/ /opt/vork/+COPY entrypoint.sh /usr/local/bin/vork-container+COPY runner.py /opt/vork/remote-runner.py+ENV PATH=/opt/vork:/opt/ffmpeg/bin:$PATH LD_LIBRARY_PATH=/opt/ffmpeg/lib \+ VORK_SLANGC=/opt/vork/slang/bin/slangc VORK_OIDN=/opt/vork/oidn/lib/libOpenImageDenoise.so.2 \+ NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=graphics,compute,utility,video+WORKDIR /job+ENTRYPOINT ["/usr/local/bin/vork-container"]+CMD ["vork", "--help"]diff --git a/tools/gpu/entrypoint.sh b/tools/gpu/entrypoint.shnew file mode 100755index 0000000..edde063--- /dev/null+++ b/tools/gpu/entrypoint.sh@@ -0,0 +1,15 @@+#!/bin/sh+set -eu+# SSH sessions do not necessarily inherit Dockerfile ENV values.+export PATH="/opt/vork:/opt/ffmpeg/bin:$PATH"+export LD_LIBRARY_PATH="/opt/ffmpeg/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"+export VORK_SLANGC="${VORK_SLANGC:-/opt/vork/slang/bin/slangc}"+export VORK_OIDN="${VORK_OIDN:-/opt/vork/oidn/lib/libOpenImageDenoise.so.2}"+# Host/container runtimes can mount /etc/vulkan/icd.d read-only. Never edit it.+# The GLX ICD needs an X path unavailable in headless containers; EGL works there.+runtime=$(mktemp -d /tmp/vork-runtime.XXXXXXXX)+trap 'rm -rf "$runtime"' EXIT HUP INT TERM+chmod 700 "$runtime"+printf '%s\n' '{"file_format_version":"1.0.1","ICD":{"library_path":"libEGL_nvidia.so.0","api_version":"1.3.0"}}' > "$runtime/nvidia.json"+export VK_DRIVER_FILES="$runtime/nvidia.json" VK_ICD_FILENAMES="$runtime/nvidia.json" XDG_RUNTIME_DIR="$runtime"+"$@"diff --git a/tools/gpu/prepare.py b/tools/gpu/prepare.pynew file mode 100644index 0000000..6c5cafa--- /dev/null+++ b/tools/gpu/prepare.py@@ -0,0 +1,37 @@+#!/usr/bin/env python3+"""Create a Docker context from a checksum-verified linux-x64 release."""+import argparse+import hashlib+from pathlib import Path+import shutil+import tarfile+++def prepare(bundle, sha256, context):+ with bundle.open('rb') as source:+ digest = hashlib.file_digest(source, 'sha256').hexdigest()+ if digest != sha256.lower():+ raise ValueError('release archive SHA256 mismatch')+ context.mkdir(parents=True, exist_ok=False)+ payload = context / 'bundle'+ with tarfile.open(bundle) as archive:+ archive.extractall(payload, filter='data')+ for name in ('vork', 'LICENSE', 'NOTICE', 'licenses', 'shaders', 'slang/bin/slangc',+ 'oidn/lib/libOpenImageDenoise.so.2'):+ if not (payload / name).exists():+ raise ValueError(f'not a complete Linux release: missing {name}')+ if (payload / 'integrations').exists():+ raise ValueError('Blender GPL bridge must not ship in renderer image')+ for name in ('Dockerfile', 'entrypoint.sh', 'runner.py'):+ shutil.copy2(Path(__file__).parent / name, context / name)+ (context / 'entrypoint.sh').chmod(0o755)+ (payload / 'vork').chmod(0o755)+++if __name__ == '__main__':+ p = argparse.ArgumentParser(description=__doc__)+ p.add_argument('--bundle', type=Path, required=True)+ p.add_argument('--sha256', required=True)+ p.add_argument('--context', type=Path, required=True)+ a = p.parse_args()+ prepare(a.bundle, a.sha256, a.context)diff --git a/tools/gpu/runner.py b/tools/gpu/runner.pynew file mode 100644index 0000000..dd6ef00--- /dev/null+++ b/tools/gpu/runner.py@@ -0,0 +1,106 @@+#!/usr/bin/env python3+"""Batch transport shared by user-account GPU templates. No listening service."""+import argparse+import io+import json+from pathlib import Path+import subprocess+import tarfile+import tempfile+import time++MAX_BYTES = 512 * 1024 * 1024+++def pack_job(directory):+ directory = directory.resolve()+ buf = io.BytesIO()+ with tarfile.open(fileobj=buf, mode='w:gz') as archive:+ for path in sorted(directory.rglob('*')):+ if path.is_symlink():+ raise ValueError(f'job symlinks are not supported: {path}')+ if path.is_file():+ archive.add(path, arcname=path.relative_to(directory), recursive=False)+ if buf.tell() > MAX_BYTES:+ raise ValueError('job archive exceeds 512 MiB; use a smaller self-contained job')+ return buf.getvalue()+++def unpack(data, destination):+ if len(data) > MAX_BYTES:+ raise ValueError('artifact archive exceeds 512 MiB')+ destination.mkdir(parents=True, exist_ok=False)+ with tarfile.open(fileobj=io.BytesIO(data)) as archive:+ archive.extractall(destination, filter='data')+++def execute(payload, scene, options, runs, timeout):+ if Path(scene).is_absolute() or '..' in Path(scene).parts:+ raise ValueError('--scene must be relative to --job')+ if any(x == '--out' or x.startswith('--out=') for x in options):+ raise ValueError('output is managed by the template; do not pass --out')+ with tempfile.TemporaryDirectory(prefix='vork-job-') as work:+ root = Path(work)+ unpack(payload, root / 'job')+ output = root / 'results'+ output.mkdir()+ cache = root / 'cache'+ cache.mkdir()+ import os+ env = dict(os.environ, VORK_CACHE_DIR=str(cache))+ gpu = subprocess.run(['nvidia-smi'], capture_output=True, text=True)+ (output / 'gpu.txt').write_text(gpu.stdout + gpu.stderr)+ records = []+ for index in range(runs):+ target = output / f'run-{index+1}'+ target.mkdir()+ command = ['vork', 'render', scene, '--out', str(target / 'video.mp4'),+ '--diagnostics', *options]+ print(f'Run {index+1}/{runs}: rendering {scene}; log returns with artifacts', flush=True)+ started = time.monotonic()+ with (target / 'render.log').open('w') as log:+ try:+ result = subprocess.run(command, cwd=root / 'job', env=env,+ stdout=log, stderr=subprocess.STDOUT, timeout=timeout)+ code = result.returncode+ except subprocess.TimeoutExpired:+ code = 124+ elapsed = time.monotonic() - started+ probe = subprocess.run(['ffprobe', '-v', 'error', '-show_streams', '-show_format',+ '-of', 'json', str(target / 'video.mp4')], capture_output=True, text=True)+ (target / 'ffprobe.json').write_text(probe.stdout or '{}')+ if code == 0 and probe.returncode:+ code = 4+ records.append(dict(run=index+1, seconds=elapsed, exit_code=code,+ command=command, probe_error=probe.stderr))+ print(json.dumps(records[-1]), flush=True)+ if code:+ break+ (output / 'job.json').write_text(json.dumps(records, indent=2) + '\n')+ buf = io.BytesIO()+ with tarfile.open(fileobj=buf, mode='w:gz') as archive:+ for path in sorted(output.rglob('*')):+ if path.is_file():+ archive.add(path, arcname=path.relative_to(output), recursive=False)+ if buf.tell() > MAX_BYTES:+ raise ValueError('results exceed 512 MiB; render a shorter clip')+ return records[-1]['exit_code'], buf.getvalue()+++if __name__ == '__main__':+ p = argparse.ArgumentParser(description=__doc__)+ p.add_argument('input', type=Path)+ p.add_argument('output', type=Path)+ p.add_argument('--scene', required=True)+ p.add_argument('--runs', type=int, default=1)+ p.add_argument('--timeout', type=int, default=1800)+ # Options after -- belong to vork, rather than to this transport.+ import sys+ argv = sys.argv[1:]+ split = argv.index('--') if '--' in argv else len(argv)+ a = p.parse_args(argv[:split])+ if not 1 <= a.runs <= 10 or a.timeout < 1:+ p.error('runs must be 1..10 and timeout positive')+ code, data = execute(a.input.read_bytes(), a.scene, argv[split+1:], a.runs, a.timeout)+ a.output.write_bytes(data)+ raise SystemExit(code)