Skip to content

Official Codebase of 3DCodeVerse

Python

scene runtime: shader text files load and are audited, the census counts shader instancing, shadows filter on r182

gaoypengd5a23267b225
diff --git a/harness/codeverse3d/prompts/scene_threejs/contract.md b/harness/codeverse3d/prompts/scene_threejs/contract.md
index 452fe163..13b60de8 100644
--- a/harness/codeverse3d/prompts/scene_threejs/contract.md
+++ b/harness/codeverse3d/prompts/scene_threejs/contract.md
@@ -8,7 +8,7 @@ src/env.js export const BOUNDS; export function heightAt(x, z); export
src/zones/<snake>.js export function build(ctx) → THREE.Group (ctx = { THREE, scene, heightAt, loaders, env, ... })
src/assets/<snake>.js export function build<Asset>(THREE, opts = {}) → THREE.Group (procedural, Y-up, on y = 0)
src/shaders/<snake>.js export function make<Name>Material(THREE, opts = {}) → THREE.ShaderMaterial | patched material
-src/lib/*.js HARNESS-OWNED effect library (44 modules) — import and call, never rewrite
+src/lib/*.js HARNESS-OWNED effect library — import and call, never rewrite
public/assets/<snake>.glb (optional) Blender-built assets — the assembled scene.js preloads each into ctx.assets['<snake>']; zones clone it (its clips play by themselves)
```
The harness serves the workspace root over http (`public/assets/` is mounted at
@@ -38,6 +38,35 @@ establishing shot that is mostly sky/ground. Dusk/night = coloured, never black
Relative imports between your own files, and `src/lib/*.js`. No CDN, no other packages,
no `three/webgpu`, no `three/tsl`.
+### Separate shader source files
+
+Write `.vert`, `.frag` and `.glsl` files under `src/shaders/`. The local server serves
+them as text. In async `createScene`, use the supplied loading manager and resolve
+paths relative to the JavaScript module, so the scene also works when packaged:
+
+```js
+const text = new THREE.FileLoader(loaders.manager); // Default response is text.
+const [vertexShader, fragmentShader] = await Promise.all([
+ text.loadAsync(new URL('./shaders/object.vert', import.meta.url).href),
+ text.loadAsync(new URL('./shaders/object.frag', import.meta.url).href),
+]);
+const material = new THREE.ShaderMaterial({ vertexShader, fragmentShader });
+```
+
+This example path is for `src/scene.js`; from a module in `src/scenes/`, use
+`../shaders/`. An optional `.glsl` helper file may be loaded and explicitly joined
+to the shader text. There is no general file `#include` resolver: Three's
+`#include <chunk>` references only its built-in shader chunks. There is no bundler,
+so `import shader from './file.frag'` and `?raw` do not load shader text.
+
+Await loading before returning the scene; missing files must reject normally rather
+than produce an empty shader. Loading is local to the workspace, never a CDN or
+external URL. Reusable asset builders remain synchronous and Node-compatible;
+perform browser loading in `createScene`, and pass already loaded text where needed.
+`update(t, dt)` changes uniforms or transforms, without loading or shader compilation.
+For GLSL 3 use `glslVersion: THREE.GLSL3`, explicit `in`/`out` varyings and a fragment
+output; let Three add the version line instead of adding a second `#version`.
+
`src/lib/` is NOT a helper SDK and the "raw language only" law does not exclude it: it is
harness-owned source shipped into this workspace, every module compiled and rendered on
this renderer, and writes to it are reverted. Reach for it before writing your own
@@ -49,13 +78,15 @@ bloom: author them at peak 1.5–4, not 20. `--no-post` / `C3D_POST=0` turns it
## Forbidden
`document.*` / `window.*` except `window.innerWidth` — never create canvases or DOM;
-`fetch`/XHR (use `loaders.gltf`); `Math.random()` (use a seeded hash `rand(i)`);
+external network requests or arbitrary `fetch`/XHR (use `loaders.gltf` for assets
+and the local FileLoader pattern above for shader text); `Math.random()` (use a seeded hash `rand(i)`);
`Date.now()`/`performance.now()` (use `t`); `requestAnimationFrame`; creating a renderer;
changing renderer settings; environment sniffing (`navigator.userAgent`, headless checks).
## Efficiency
-InstancedMesh for anything repeated > 5×; textures only procedural (DataTexture /
-CanvasTexture is NOT available); `update` allocates nothing and traverses nothing.
+InstancedMesh for anything repeated > 5×; textures: the shipped procedural materials
+(including their DataTextures) or the provided `loaders.texture` for textures actually
+present in the workspace; `update` allocates nothing and traverses nothing.
## Naming
Zones are Groups named PascalCase (plan zone names); assets Groups PascalCase; every
diff --git a/harness/codeverse3d/prompts/scene_threejs/system.md b/harness/codeverse3d/prompts/scene_threejs/system.md
index d6e92907..513150e6 100644
--- a/harness/codeverse3d/prompts/scene_threejs/system.md
+++ b/harness/codeverse3d/prompts/scene_threejs/system.md
@@ -1,8 +1,15 @@
You are a three.js + GLSL author writing RAW ESM modules for a multi-file scene in a
-headless harness. No SDKs, no DOM, no `fetch`, no CDN imports: `import * as THREE from
+headless harness. No SDKs, no DOM, no external network/CDN imports: `import * as THREE from
'three'` and your own relative modules, nothing else. The harness owns the renderer, the
render loop and the export — you build the scene graph and the cameras.
+Local shader files are supported: write `.vert`, `.frag` or `.glsl` under `src/`,
+then await `new THREE.FileLoader(loaders.manager).loadAsync(new URL('./shaders/name.frag',
+import.meta.url).href)` inside async `createScene`. Assemble the loaded text into a
+ShaderMaterial/RawShaderMaterial before returning. These are ordinary source files,
+not JavaScript imports; no bundler `?raw` syntax or remote requests. Keep synchronous
+asset builders free of loading, and never fetch/recompile during `update`.
+
This track scores lower than any other in the harness (baseline mean **0.297** over 32
recorded runs) and the reason is not modelling. It is that **the picture is black**.
diff --git a/harness/codeverse3d/spatial/gl_render.py b/harness/codeverse3d/spatial/gl_render.py
index 417ea77d..62e5e53a 100644
--- a/harness/codeverse3d/spatial/gl_render.py
+++ b/harness/codeverse3d/spatial/gl_render.py
@@ -134,7 +134,10 @@ class GlHost:
# ------------------------------------------------------------------ internals
def _run(self, job: dict[str, Any], out_dir: Path) -> GlResult:
- out_dir = Path(out_dir)
+ # The subprocess starts inside out_dir. A relative job path would be
+ # resolved against that directory a second time and appear to crash
+ # before it could write any result (observed with --out examples/...).
+ out_dir = Path(out_dir).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / RESULT_NAME).unlink(missing_ok=True)
for p in (out_dir / "frames").glob("*.png"):
diff --git a/harness/runtime_js/lib/browser/renderer.js b/harness/runtime_js/lib/browser/renderer.js
index 791f4baf..c8f81e12 100644
--- a/harness/runtime_js/lib/browser/renderer.js
+++ b/harness/runtime_js/lib/browser/renderer.js
@@ -1,7 +1,7 @@
// THE WebGLRenderer factory for every page-side rig (object renders through
// studio.js/render_rig.js, scenes through scene_host.mjs): one set of fixed
// harness settings — antialias, pixel ratio 1, sRGB output, ACES tone mapping,
-// PCF soft shadows, preserveDrawingBuffer (canvas readback) — so an object
+// filtered PCF shadows, preserveDrawingBuffer (canvas readback) — so an object
// render and a scene render expose the same colour pipeline.
//
// import { makeRenderer, rendererString } from '/__runtime/lib/browser/renderer.js';
@@ -29,7 +29,11 @@ export function makeRenderer(canvas, width, height, { transparent = false, logDe
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.0;
renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ // r182 removed PCFSoftShadowMap from WebGLProgram's type mapping. Keeping
+ // that deprecated value silently compiles SHADOWMAP_TYPE_BASIC: hard texel
+ // blocks on thin grass, candles and sand, even with a 4096 map. PCFShadowMap
+ // selects the supported filtered shadow shader on the installed runtime.
+ renderer.shadowMap.type = THREE.PCFShadowMap;
return renderer;
}
diff --git a/harness/runtime_js/lib/census.mjs b/harness/runtime_js/lib/census.mjs
index 8522f549..13a6e94b 100644
--- a/harness/runtime_js/lib/census.mjs
+++ b/harness/runtime_js/lib/census.mjs
@@ -9,10 +9,38 @@
export function geometryTriangles(geometry) {
if (!geometry || !geometry.attributes || !geometry.attributes.position) return 0;
const count = geometry.index ? geometry.index.count : geometry.attributes.position.count;
- const range = geometry.drawRange ? Math.min(geometry.drawRange.count, count) : count;
+ const start = Math.max(0, geometry.drawRange?.start || 0);
+ const range = Math.max(0, Math.min(geometry.drawRange?.count ?? count, count - start));
return Math.floor(range / 3);
}
+/** Draw multiplicity, including shader-driven InstancedBufferGeometry cards.
+ * Three derives an implicit capacity from instanced attributes on first bind;
+ * before that bind we can infer a conservative finite capacity from the same
+ * buffers. Matrix instances use object.count, not geometry.instanceCount.
+ */
+export function geometryInstances(object) {
+ if (object.isInstancedMesh) return Math.max(0, Math.floor(object.count));
+ const geometry = object.geometry;
+ if (!geometry?.isInstancedBufferGeometry) return 1;
+ let capacity = geometry._maxInstanceCount;
+ if (capacity === undefined) {
+ capacity = Infinity;
+ // Before binding there is no compiled attribute-usage information. Once
+ // Three has bound a program, its capacity is authoritative: unused shorter
+ // attributes must not reduce the actual number of submitted instances.
+ for (const attribute of Object.values(geometry.attributes)) {
+ const buffer = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
+ if (buffer.isInstancedBufferAttribute || buffer.isInstancedInterleavedBuffer) {
+ capacity = Math.min(capacity, buffer.count * buffer.meshPerAttribute);
+ }
+ }
+ }
+ const count = Math.min(geometry.instanceCount, capacity);
+ // An unbounded geometry with no instance attribute has no finite draw budget.
+ return Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0;
+}
+
function isMeshLike(obj) {
return !!(obj.isMesh || obj.isSkinnedMesh || obj.isInstancedMesh);
}
diff --git a/harness/runtime_js/lib/glsl_audit.mjs b/harness/runtime_js/lib/glsl_audit.mjs
index 45afc858..d23bd444 100644
--- a/harness/runtime_js/lib/glsl_audit.mjs
+++ b/harness/runtime_js/lib/glsl_audit.mjs
@@ -40,9 +40,25 @@ function finding(file, line, kind, message, severity = 'error') {
return { file, line, kind, message, severity };
}
+export function isShaderSource(file) {
+ return /\.(glsl|vert|frag)$/.test(file);
+}
+
/** Audit one file; returns findings. */
export function auditFile(file, source, { sceneUsesFog = false } = {}) {
const findings = [];
+ if (isShaderSource(file)) {
+ // Raw files may be joined into another shader or used by RawShaderMaterial.
+ // Their JS uniform bindings, material type and assembled declarations are
+ // unknown here; compile/runtime audits own those cross-file questions.
+ source.split('\n').forEach((line, i) => {
+ if (/^\s*#include\b/.test(line) && !INCLUDE_OK_RE.test(line)) {
+ findings.push(finding(file, i + 1, 'include_not_alone',
+ `'#include <chunk>' must be ALONE on its line (found: ${line.trim().slice(0, 80)})`));
+ }
+ });
+ return findings;
+ }
const strings = extractGlslStrings(source);
if (!strings.length) return findings;
const isRaw = /RawShaderMaterial/.test(source);
@@ -111,13 +127,14 @@ export function hasGlsl(source) {
return extractGlslStrings(source).length > 0;
}
-/** Locate `sourceLine` (trimmed text) in GLSL strings of files: unique → {file, line}. */
+/** Locate compiler text in raw shader files or GLSL strings inside JS modules. */
export function locateSourceLine(files, sourceLine) {
const needle = String(sourceLine || '').trim();
if (needle.length < 3) return { file: '', line: null, candidates: 0 };
const hits = [];
for (const { file, text } of files) {
- for (const s of extractGlslStrings(text)) {
+ const blocks = isShaderSource(file) ? [{ text, line: 1 }] : extractGlslStrings(text);
+ for (const s of blocks) {
s.text.split('\n').forEach((ln, i) => { if (ln.trim() === needle) hits.push({ file, line: s.line + i }); });
}
}
diff --git a/harness/runtime_js/lib/host_census.mjs b/harness/runtime_js/lib/host_census.mjs
index dc026957..d8e1b616 100644
--- a/harness/runtime_js/lib/host_census.mjs
+++ b/harness/runtime_js/lib/host_census.mjs
@@ -7,7 +7,7 @@
*/
import { classifyBackdrop, drawableBox } from './backdrop.mjs';
-import { geometryTriangles as triCount } from './census.mjs';
+import { geometryTriangles as triCount, geometryInstances } from './census.mjs';
import { placementTable } from './host_placement.mjs';
export function isCustomShader(mat, THREE) {
@@ -70,13 +70,12 @@ function walkGroup(root, THREE) {
f.sizes.push(Math.max(size.x, size.y, size.z));
};
root.updateMatrixWorld(true);
- root.traverse((o) => {
- if (!o.visible) return;
+ root.traverseVisible((o) => {
if (o.isLight) lights += 1;
if (!(o.isMesh || o.isPoints || o.isLine || o.isSprite)) return;
- const count = o.isInstancedMesh ? o.count : 1;
+ const count = geometryInstances(o);
if (o.isMesh) { meshes += 1; instances += count; }
- tris += triCount(o.geometry) * count;
+ if (o.isMesh) tris += triCount(o.geometry) * count;
const mats = Array.isArray(o.material) ? o.material : [o.material];
if (mats.some((m) => isCustomShader(m, THREE))) custom += 1;
let mb = drawableBox(o, THREE);
diff --git a/harness/runtime_js/lib/shader_report.mjs b/harness/runtime_js/lib/shader_report.mjs
index 9c4bfb1c..9cfa1caf 100644
--- a/harness/runtime_js/lib/shader_report.mjs
+++ b/harness/runtime_js/lib/shader_report.mjs
@@ -15,17 +15,17 @@
import fs from 'node:fs';
import path from 'node:path';
-import { auditFile, fixHintFor, hasGlsl, locateSourceLine } from './glsl_audit.mjs';
+import { auditFile, fixHintFor, hasGlsl, isShaderSource, locateSourceLine } from './glsl_audit.mjs';
import { errorSummary } from './host_page.mjs';
-import { listJsFiles } from './syntax_check.mjs';
+import { listSourceFiles } from './syntax_check.mjs';
/**
- * All .js/.mjs sources under <root>/<sub> as [{file, text}] (posix rel paths,
- * sorted). The directory walk itself is `syntax_check.listJsFiles` — the one
- * source-file walker in runtime_js.
+ * JavaScript and standalone GLSL under <root>/<sub>, with sorted relative paths.
+ * The shared walker keeps raw shader files out of the JavaScript syntax parser.
*/
export function listSources(root, sub = 'src') {
- return listJsFiles(path.join(root, sub)).map((p) => ({
+ return listSourceFiles(path.join(root, sub),
+ new Set(['.js', '.mjs', '.glsl', '.vert', '.frag'])).map((p) => ({
file: path.relative(root, p).split(path.sep).join('/'),
text: fs.readFileSync(p, 'utf8'),
}));
@@ -62,7 +62,8 @@ export function staticShaderReport(ws, module = null) {
}
const report = {
ok: false, ws, module: module || null,
- static: { files: auditTargets.length, glsl_files: auditTargets.filter((f) => hasGlsl(f.text)).length },
+ static: { files: auditTargets.length,
+ glsl_files: auditTargets.filter((f) => isShaderSource(f.file) || hasGlsl(f.text)).length },
compile: null, errors, warnings,
};
return { report, files };
@@ -79,6 +80,12 @@ export function staticShaderReport(ws, module = null) {
export async function compileIntoReport(report, files, host) {
const { page, boot } = host;
const { errors, warnings } = report;
+ // Literals precede JS joins/replacements and externally loaded declarations.
+ // A successful forced compile checks includes and uniform declarations in
+ // the assembled program. It cannot prove JS uniform bindings: an unbound
+ // uniform still compiles and stays 0, so those errors remain authoritative.
+ const staticLanguageErrors = new Set(errors.filter((e) =>
+ e.kind === 'include_not_alone' || e.kind === 'undeclared_uniform'));
if (!boot.ok) {
errors.push({ file: 'src/scene.js', line: null, kind: 'boot', message: `scene did not boot at stage '${boot.stage}': ${boot.error}`.slice(0, 1200), fix_hint: 'fix the import/runtime error first; then compile again' });
} else {
@@ -97,6 +104,15 @@ export async function compileIntoReport(report, files, host) {
(a.severity === 'error' ? errors : warnings).push({ file: '(runtime material)', line: null, kind: a.kind, material: a.material, message: a.message, fix_hint: a.severity === 'error' ? a.message : '' });
}
report.compile = { ms: comp.compile_ms, programs: comp.programs, custom_materials: comp.custom_materials, renderer: boot.renderer, gpu: host.gpu };
+ if (comp.programs > 0 && shaderErrors.length === 0) {
+ for (let i = errors.length - 1; i >= 0; i--) {
+ const e = errors[i];
+ if (!staticLanguageErrors.has(e)) continue;
+ errors.splice(i, 1);
+ warnings.push({ ...e, fix_hint: '', validation: 'runtime_compile_passed',
+ message: `${e.message} — source-only warning: all evaluated shader programs compiled successfully; JavaScript may transform this literal or join external source before use.` });
+ }
+ }
}
const es = errorSummary(host.errors, boot);
for (const c of es.shader_console) {
diff --git a/harness/runtime_js/lib/syntax_check.mjs b/harness/runtime_js/lib/syntax_check.mjs
index ce2bc9c1..5ceff040 100644
--- a/harness/runtime_js/lib/syntax_check.mjs
+++ b/harness/runtime_js/lib/syntax_check.mjs
@@ -38,8 +38,8 @@ export function checkFiles(files) {
return bad;
}
-/** Recursively list *.js / *.mjs under dir (skipping node_modules and dot entries). */
-export function listJsFiles(dir) {
+/** Recursively list source suffixes, skipping node_modules and dot entries. */
+export function listSourceFiles(dir, suffixes = new Set(['.js', '.mjs'])) {
const out = [];
if (!fs.existsSync(dir)) return out;
const walk = (d) => {
@@ -47,13 +47,18 @@ export function listJsFiles(dir) {
if (ent.name === 'node_modules' || ent.name.startsWith('.')) continue;
const p = path.join(d, ent.name);
if (ent.isDirectory()) walk(p);
- else if (/\.(m?js)$/.test(ent.name)) out.push(p);
+ else if (suffixes.has(path.extname(ent.name))) out.push(p);
}
};
walk(dir);
return out.sort();
}
+/** Only JavaScript is passed to the ES module syntax parser. */
+export function listJsFiles(dir) {
+ return listSourceFiles(dir);
+}
+
/** First file under srcDir that fails to parse, or null (one child process for all of them:
* vm modules need the flag this process was not started with). */
export function findSyntaxError(srcDir) {
diff --git a/harness/tests/graphics/test_gl_host.py b/harness/tests/graphics/test_gl_host.py
index 0741ae79..022a5442 100644
--- a/harness/tests/graphics/test_gl_host.py
+++ b/harness/tests/graphics/test_gl_host.py
@@ -66,6 +66,16 @@ def test_gpu_then_cpu_fallback_is_cached(tmp_path, fake_runner, monkeypatch):
assert (tmp_path / "o2" / gl_render.JOB_NAME).is_file() and json.loads((tmp_path / "o2" / gl_render.JOB_NAME).read_text())["mode"] == "program"
+def test_relative_output_path_survives_runner_working_directory(tmp_path, fake_runner, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ result = GlHost(gpu="off").render_fragment_shader("src", Path("relative/render"),
+ width=32, height=18, times=(0.0,))
+ assert result.ok, result.stderr_tail
+ frame = Path(result.frames[0].path)
+ assert frame.is_file() and frame.is_relative_to(tmp_path / "relative/render")
+ assert not (tmp_path / "relative/render/relative").exists()
+
+
def test_gpu_on_failure_raises_and_crash_timeout_are_typed(tmp_path, fake_runner, monkeypatch):
monkeypatch.setenv("FAKE_MODE", "gpu_fail")
with pytest.raises(GlHostError):
diff --git a/harness/tests/scene_runtime/test_census_instances.py b/harness/tests/scene_runtime/test_census_instances.py
new file mode 100644
index 00000000..f90eaba8
--- /dev/null
+++ b/harness/tests/scene_runtime/test_census_instances.py
@@ -0,0 +1,97 @@
+"""Scene budgets include shader-instanced geometry and respect hidden parents."""
+import pytest
+
+from codeverse3d.config import get_settings
+from tests.scene_runtime.conftest import needs_node, run_node_json
+from tests.scene_runtime.lib._probe import compile_scene
+
+pytestmark = [pytest.mark.node, needs_node]
+RUNTIME_JS = get_settings().runtime_js_dir()
+
+
+def test_shader_instances_capacity_draw_range_and_hidden_ancestors():
+ out = run_node_json("""
+import * as THREE from 'three';
+import {sceneCensus} from './lib/host_census.mjs';
+import {geometryTriangles,geometryInstances} from './lib/census.mjs';
+const scene=new THREE.Scene(),zone=new THREE.Group();scene.add(zone);
+const geo=new THREE.InstancedBufferGeometry().copy(new THREE.PlaneGeometry());
+geo.instanceCount=Infinity;
+geo.setAttribute('aOffset',new THREE.InstancedBufferAttribute(new Float32Array(12),3,false,2));
+const cards=new THREE.Mesh(geo,new THREE.MeshBasicMaterial());cards.name='Cards';zone.add(cards);
+const full=sceneCensus(scene,THREE).totals;geo.instanceCount=3;
+const limited=sceneCensus(scene,THREE).totals;geo.setDrawRange(3,99);
+const range=sceneCensus(scene,THREE).totals;geo.setDrawRange(10,99);const empty=geometryTriangles(geo);
+const points=new THREE.Points(new THREE.BoxGeometry(),new THREE.PointsMaterial());zone.add(points);
+const lines=new THREE.LineSegments(new THREE.BoxGeometry(),new THREE.LineBasicMaterial());zone.add(lines);
+const nonTriangles=sceneCensus(scene,THREE).totals.triangles;
+zone.visible=false;const hidden=sceneCensus(scene,THREE).totals;
+const instanced=new THREE.InstancedMesh(new THREE.BoxGeometry(),new THREE.MeshBasicMaterial(),7);
+instanced.count=2;
+console.log(JSON.stringify({full,limited,range,empty,nonTriangles,hidden,matrix:geometryInstances(instanced)}));
+""".replace("'./lib/", f"'{RUNTIME_JS}/lib/"))
+ assert out["full"]["instances"] == 8 and out["full"]["triangles"] == 16
+ assert out["limited"]["instances"] == 3 and out["limited"]["triangles"] == 6
+ assert out["range"]["triangles"] == 3 and out["empty"] == 0
+ assert out["nonTriangles"] == 0 and out["matrix"] == 2
+ assert out["hidden"]["meshes"] == out["hidden"]["instances"] == out["hidden"]["triangles"] == 0
+
+
+def test_census_matches_actual_gpu_instanced_triangle_submission():
+ code, output = compile_scene("""
+import * as THREE from 'three';
+import {sceneCensus} from '/__runtime/lib/host_census.mjs';
+export function createScene({renderer}) {
+ const scene=new THREE.Scene(),geo=new THREE.InstancedBufferGeometry().copy(new THREE.PlaneGeometry());
+ geo.instanceCount=Infinity;
+ geo.setAttribute('aOffset',new THREE.InstancedBufferAttribute(new Float32Array(12),3,false,2));
+ const material=new THREE.ShaderMaterial({vertexShader:
+ 'attribute vec3 aOffset;void main(){gl_Position=projectionMatrix*modelViewMatrix*vec4(position+aOffset,1.0);}',
+ fragmentShader:'void main(){gl_FragColor=vec4(.3,.6,.8,1.0);}'});
+ scene.add(new THREE.Mesh(geo,material));
+ const camera=new THREE.PerspectiveCamera(45,1,.01,100);camera.position.z=3;
+ const target=new THREE.WebGLRenderTarget(32,32),previous=renderer.getRenderTarget();
+ try {
+ for(const start of [0,3]) {
+ geo.setDrawRange(start,Infinity);
+ const census=sceneCensus(scene,THREE).totals;
+ renderer.setRenderTarget(target);renderer.render(scene,camera);
+ if(census.triangles!==renderer.info.render.triangles || census.instances!==8)
+ throw new Error(JSON.stringify({census,render:renderer.info.render}));
+ }
+ } finally {renderer.setRenderTarget(previous);target.dispose();}
+ return {scene,cameras:[{name:'a',position:[0,0,3],lookAt:[0,0,0]}]};
+}
+""", audit_module="src/scene.js")
+ assert code == 0, output
+
+
+def test_bound_gpu_capacity_ignores_unused_short_instanced_attributes():
+ """Only attributes used by the linked program constrain Three's draw."""
+ code, output = compile_scene("""
+import * as THREE from 'three';
+import {sceneCensus} from '/__runtime/lib/host_census.mjs';
+export function createScene({renderer}) {
+ const scene=new THREE.Scene(),geo=new THREE.InstancedBufferGeometry().copy(new THREE.PlaneGeometry());
+ geo.setAttribute('activeOffset',new THREE.InstancedBufferAttribute(new Float32Array(24),3));
+ geo.setAttribute('unusedShort',new THREE.InstancedBufferAttribute(new Float32Array(3),3));
+ const material=new THREE.ShaderMaterial({vertexShader:
+ 'attribute vec3 activeOffset;void main(){gl_Position=projectionMatrix*modelViewMatrix*vec4(position+activeOffset,1.0);}',
+ fragmentShader:'void main(){gl_FragColor=vec4(.3,.6,.8,1.0);}'});
+ const mesh=new THREE.Mesh(geo,material);mesh.frustumCulled=false;scene.add(mesh);
+ const camera=new THREE.PerspectiveCamera(45,1,.01,100);camera.position.z=3;
+ const target=new THREE.WebGLRenderTarget(32,32),previous=renderer.getRenderTarget();
+ try {
+ for(const requested of [8,3,Infinity]) {
+ geo.instanceCount=requested;
+ renderer.setRenderTarget(target);renderer.render(scene,camera);
+ const census=sceneCensus(scene,THREE).totals,expected=Math.min(requested,8);
+ if(geo._maxInstanceCount!==8 || census.instances!==expected ||
+ census.triangles!==renderer.info.render.triangles || census.triangles!==expected*2)
+ throw new Error(JSON.stringify({requested,census,capacity:geo._maxInstanceCount,render:renderer.info.render}));
+ }
+ } finally {renderer.setRenderTarget(previous);target.dispose();}
+ return {scene,cameras:[{name:'a',position:[0,0,3],lookAt:[0,0,0]}]};
+}
+""", audit_module="src/scene.js")
+ assert code == 0, output
diff --git a/harness/tests/scene_runtime/test_external_shaders.py b/harness/tests/scene_runtime/test_external_shaders.py
new file mode 100644
index 00000000..1857718a
--- /dev/null
+++ b/harness/tests/scene_runtime/test_external_shaders.py
@@ -0,0 +1,109 @@
+"""Standalone scene shader files load locally and report their own source lines."""
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+
+from tests.scene_runtime.conftest import RUNTIME_JS, needs_browser, needs_node, run_node_json
+
+SCENE = """import * as THREE from 'three';
+export async function createScene({loaders}) {
+ const text = new THREE.FileLoader(loaders.manager).setResponseType('text');
+ const [vertexShader, fragment, common] = await Promise.all(
+ ['panel.vert', 'panel.frag', 'palette.glsl'].map(file =>
+ text.loadAsync(new URL('./shaders/' + file, import.meta.url).href)));
+ const material = new THREE.ShaderMaterial({name:'StandaloneFiles', vertexShader,
+ fragmentShader:common + '\\n' + fragment, uniforms:{uTime:{value:0}}, fog:false});
+ const scene = new THREE.Scene();
+ const geometry = new THREE.BoxGeometry(2,2,2);
+ scene.add(new THREE.Mesh(geometry, material));
+ return {scene, cameras:[{name:'probe',position:[3,2,4],lookAt:[0,0,0]}],
+ update(t){material.uniforms.uTime.value=t;},
+ dispose(){geometry.dispose();material.dispose();}};
+}
+"""
+VERTEX = "varying vec2 vUv;\nvoid main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}\n"
+COMMON = "vec3 panelColor(vec2 uv, float t){return vec3(uv,0.5+0.2*sin(t));}\n"
+FRAGMENT = "uniform float uTime;\nvarying vec2 vUv;\nvoid main(){\n gl_FragColor=vec4(panelColor(vUv,uTime),1.0);\n}\n"
+
+
+def stage(tmp_path, *, broken=False):
+ shader = tmp_path / "src/shaders"
+ shader.mkdir(parents=True)
+ (tmp_path / "src/scene.js").write_text(SCENE)
+ (shader / "panel.vert").write_text(VERTEX)
+ (shader / "palette.glsl").write_text(COMMON)
+ fragment = FRAGMENT.replace("panelColor(vUv,uTime)", "panelColor(vUv,uTime)*missingExternalFactor") if broken else FRAGMENT
+ (shader / "panel.frag").write_text(fragment)
+ return tmp_path
+
+
+@needs_node
+def test_shader_files_are_audited_without_becoming_javascript(tmp_path):
+ root = stage(tmp_path)
+ result = run_node_json(f"""
+import {{staticShaderReport}} from './lib/shader_report.mjs';
+import {{findSyntaxError}} from './lib/syntax_check.mjs';
+import {{auditFile,locateSourceLine}} from './lib/glsl_audit.mjs';
+const ws={json.dumps(str(root))};
+const {{report,files}}=staticShaderReport(ws);
+console.log(JSON.stringify({{report,syntax:findSyntaxError(ws+'/src'),
+ selected:staticShaderReport(ws,'src/shaders/panel.frag').report,
+ helper:auditFile('src/shaders/helper.glsl','float clock(){{return uTime;}}'),
+ malformed:auditFile('src/shaders/bad.frag','#include <common> void main(){{}}'),
+ location:locateSourceLine(files,'gl_FragColor=vec4(panelColor(vUv,uTime),1.0);')}}));
+""")
+ assert result["report"]["static"] == {"files": 4, "glsl_files": 3}
+ assert result["report"]["errors"] == []
+ assert result["selected"]["static"] == {"files": 1, "glsl_files": 1}
+ assert result["selected"]["errors"] == []
+ assert result["syntax"] is None
+ assert result["helper"] == [] # A helper's uniforms may be declared in a different file.
+ assert result["malformed"][0]["kind"] == "include_not_alone"
+ assert result["location"] == {"file": "src/shaders/panel.frag", "line": 4, "candidates": 1}
+
+
+@needs_browser
[email protected]("broken", [False, True])
+def test_real_gpu_compiles_external_sources_and_maps_failures(tmp_path, broken):
+ root = stage(tmp_path, broken=broken)
+ proc = subprocess.run(["node", str(RUNTIME_JS / "check_shaders.mjs"), "--ws", str(root)],
+ capture_output=True, text=True, timeout=120)
+ assert proc.returncode == (1 if broken else 0), proc.stdout + proc.stderr
+ report = json.loads(proc.stdout.strip().splitlines()[-1])
+ assert report["static"] == {"files": 4, "glsl_files": 3}
+ assert report["compile"]["programs"] > 0
+ if broken:
+ failures = [item for item in report["errors"] if item["kind"] == "compile"]
+ assert failures
+ assert any(item["file"] == "src/shaders/panel.frag" and item["line"] == 4
+ and "missingExternalFactor" in item["message"] for item in failures), failures
+ else:
+ assert report["ok"] and report["errors"] == []
+
+
+@needs_browser
[email protected]("declaration", [True, False])
+def test_external_uniform_header_can_be_joined_with_inline_glsl(tmp_path, declaration):
+ root = stage(tmp_path)
+ (root / "src/shaders/panel.frag").write_text("uniform float uTime;\n" if declaration else "// No declaration\n")
+ scene = SCENE.replace("fragmentShader:common + '\\n' + fragment,",
+ "fragmentShader:common + '\\n' + fragment + `\\nvoid main(){gl_FragColor=vec4(vec3(uTime),1.0);}`, ")
+ assert scene != SCENE
+ (root / "src/scene.js").write_text(scene)
+ proc = subprocess.run(["node", str(RUNTIME_JS / "check_shaders.mjs"), "--ws", str(root)],
+ capture_output=True, text=True, timeout=120)
+ assert proc.returncode == (0 if declaration else 1), proc.stdout + proc.stderr
+ report = json.loads(proc.stdout.strip().splitlines()[-1])
+ if declaration:
+ assert report["ok"] and report["errors"] == []
+ assert any(item["kind"] == "undeclared_uniform" and item.get("validation") == "runtime_compile_passed"
+ for item in report["warnings"])
+ else:
+ assert any(item["kind"] == "compile" for item in report["errors"])
+ assert any(item["kind"] == "undeclared_uniform" for item in report["errors"])
diff --git a/harness/tests/scene_runtime/test_shader_report.py b/harness/tests/scene_runtime/test_shader_report.py
new file mode 100644
index 00000000..b0930926
--- /dev/null
+++ b/harness/tests/scene_runtime/test_shader_report.py
@@ -0,0 +1,62 @@
+"""Runtime compilation must arbitrate uncertain source-literal include findings."""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from tests.scene_runtime.conftest import needs_node, run_node_json
+
+pytestmark = [pytest.mark.node, needs_node]
+
+
+def compile_report(*, programs=2, shader_errors=None, boot_ok=True, uniform_error=False):
+ body = """
+import { compileIntoReport } from './lib/shader_report.mjs';
+const options = OPTIONS;
+const report = {errors: [{kind:'include_not_alone', file:'src/scene.js', line:7,
+ message:'include inside a source literal', fix_hint:'put include on its own line'}], warnings:[]};
+if(options.uniform_error) report.errors.push({kind:'unbound_uniform', message:'uTime missing'});
+const comp = {shader_errors:options.shader_errors || [], material_audit:[],
+ programs:options.programs, custom_materials:1, compile_ms:1};
+const host = {boot:{ok:options.boot_ok, renderer:'test', stage:'ready', error:''},
+ gpu:false, errors:{console:[],page:[],network:[],warnings:[],shader_console:[]}, page:{evaluate:async()=>comp}};
+await compileIntoReport(report, [], host);
+console.log(JSON.stringify(report));
+""".replace(
+ "OPTIONS",
+ json.dumps(
+ dict(
+ programs=programs,
+ shader_errors=shader_errors,
+ boot_ok=boot_ok,
+ uniform_error=uniform_error,
+ )
+ ),
+ )
+ return run_node_json(body)
+
+
+def test_successful_evaluated_shader_retains_static_advice_without_false_failure():
+ result = compile_report()
+ assert result["errors"] == []
+ assert result["warnings"][0]["kind"] == "include_not_alone"
+ assert result["warnings"][0]["validation"] == "runtime_compile_passed"
+
+
+def test_runtime_compile_failure_is_still_a_hard_error():
+ result = compile_report(
+ shader_errors=[dict(stage="fragment", message="syntax error", source_line="bad")]
+ )
+ assert {e["kind"] for e in result["errors"]} == {"include_not_alone", "compile"}
+ assert not result["warnings"]
+
+
+def test_no_compiled_programs_and_boot_failure_cannot_override_source_errors():
+ for result in (compile_report(programs=0), compile_report(boot_ok=False)):
+ assert "include_not_alone" in {e["kind"] for e in result["errors"]}
+
+
+def test_compile_success_does_not_clear_missing_uniform_binding():
+ result = compile_report(uniform_error=True)
+ assert [e["kind"] for e in result["errors"]] == ["unbound_uniform"]
diff --git a/harness/tests/scene_runtime/test_shadow_filter.py b/harness/tests/scene_runtime/test_shadow_filter.py
new file mode 100644
index 00000000..3bd25e9a
--- /dev/null
+++ b/harness/tests/scene_runtime/test_shadow_filter.py
@@ -0,0 +1,50 @@
+"""The shared renderer must compile filtered shadows on the installed Three.
+
+Checking the enum alone missed r182's removal of PCFSoftShadowMap from the
+WebGLProgram mapping: that old enum compiled BASIC without a runtime error.
+Inspect the actual linked fragment shader of a shadow-receiving material.
+"""
+import json
+import subprocess
+
+import pytest
+
+from tests.scene_runtime.conftest import RUNTIME_JS, needs_browser
+
+
+@needs_browser
+def test_linked_gpu_program_uses_filtered_shadows(tmp_path):
+ root = tmp_path / "scene"
+ (root / "src").mkdir(parents=True)
+ (root / "src/scene.js").write_text("""
+import * as THREE from 'three';
+export function createScene({renderer}) {
+ const scene=new THREE.Scene();
+ const sun=new THREE.DirectionalLight(0xffffff,3);
+ sun.position.set(2,4,1);sun.castShadow=true;scene.add(sun);
+ const mesh=new THREE.Mesh(new THREE.BoxGeometry(),new THREE.MeshStandardMaterial());
+ mesh.castShadow=true;mesh.receiveShadow=true;scene.add(mesh);
+ window.shadowProbe=()=>renderer.info.programs.map(p=>
+ renderer.getContext().getShaderSource(p.fragmentShader));
+ return {scene,cameras:[{name:'a',position:[3,2,4],lookAt:[0,0,0],fov:45}],update(){}};
+}
+""")
+ script = tmp_path / "probe.mjs"
+ script.write_text(f"""
+import {{openHost}} from {json.dumps((RUNTIME_JS / 'lib/host_page.mjs').as_uri())};
+const host=await openHost({json.dumps(str(root))},{{width:128,height:128,post:false}});
+try {{
+ if(!host.boot.ok)throw new Error(host.boot.error);
+ await host.page.evaluate(()=>window.__c3v.renderAt(window.__c3v.cameras()[0],0));
+ const fragments=await host.page.evaluate(()=>window.shadowProbe());
+ const receiving=fragments.filter(s=>s.includes('#define USE_SHADOWMAP'));
+ console.log(JSON.stringify({{n:receiving.length,
+ filtered:receiving.every(s=>s.includes('#define SHADOWMAP_TYPE_PCF')),
+ basic:receiving.some(s=>s.includes('#define SHADOWMAP_TYPE_BASIC'))}}));
+}} finally {{await host.close();}}
+""")
+ proc = subprocess.run(["node", str(script)], capture_output=True, text=True, timeout=90)
+ assert proc.returncode == 0, proc.stderr
+ result = json.loads(proc.stdout.strip().splitlines()[-1])
+ assert result["n"] > 0 and result["filtered"] and not result["basic"], result