Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Register the surface field inputs from the mesh and instance path so other bundles do not carry them (issue #597)

Nguyen Xuan An6f81a9052cc9
diff --git a/changes/597-field-surface-sampling.size.md b/changes/597-field-surface-sampling.size.md
index af1a6b91..aae9320b 100644
--- a/changes/597-field-surface-sampling.size.md
+++ b/changes/597-field-surface-sampling.size.md
@@ -1,6 +1 @@
-- entry:light-bake: its field-selection code now carries the surface inputs of fields (about 840 bytes gzip, `src/mesh-field-surfaces.js`); the BVH query itself stays in the mesh chunk.
-- entry:light-bake-gpu: the same field module growth as entry:light-bake, in its shared mesh-selection path.
-- entry:ground-bounce: the same field module growth, about 840 bytes gzip.
-- entry:floor-sky-visibility: the same field module growth, about 840 bytes gzip.
-- entry:water-reflection: the same field module growth, about 840 bytes gzip.
- scene:agent-scene+lazy: the surface inputs and the BVH query wrapper load only with the mesh chunk and buy scatter that avoids paths and follows terrain, plus density maps stored as vertex groups; the core bundle shrinks by 4 bytes because new capability text is paid for by shorter notes.
diff --git a/src/mesh-field-surfaces.js b/src/mesh-field-surfaces.js
index 3354e964..7353683c 100644
--- a/src/mesh-field-surfaces.js
+++ b/src/mesh-field-surfaces.js
@@ -1,3 +1,4 @@
+import { registerFieldSource } from './mesh-fields.js';
import { compileNode, constantScalar, isBoundedNumber, isPlainObject, scalarValue, vectorValue } from './expression.js';
// Field inputs that read another surface: "nearest" (Geometry Proximity and Sample Nearest Surface) and "raycast"
@@ -86,7 +87,7 @@ function readResult(read, queryAt, miss) {
}
function chargedQuery(state, run) {
- const { budget } = state.context.surfaceLookup;
+ const { budget } = lookupOf(state.context);
const result = run(budget.remaining);
budget.remaining -= result.triangleTests;
if (budget.remaining <= 0) throw new RangeError('Field expression searched too many surface triangles. Use fewer elements or a simpler surface.');
@@ -100,7 +101,7 @@ export function compileNearest(node, state, depth, positionInput) {
const surface = checkedSurface(settings, 'nearest');
const read = checkedRead(settings, NEAREST_READS, 'distance', 'nearest');
const [partX, partY, partZ] = atParts(settings, state, depth, 'nearest', positionInput);
- const lookup = state.context.surfaceLookup;
+ const lookup = lookupOf(state.context);
if (!lookup) return VECTOR_READS.has(read) ? vectorValue(() => 0, () => 0, () => 0) : constantScalar(0);
const surfaceIndex = lookup.indexOf(surface);
return readResult(read, index => chargedQuery(state, remaining => surfaceIndex.nearest([partX(index), partY(index), partZ(index)], { maxTriangleTests: remaining })), 0);
@@ -119,7 +120,7 @@ export function compileRaycast(node, state, depth, positionInput) {
if (settings.miss !== undefined && !isBoundedNumber(settings.miss)) throw surfaceError('raycast miss must be a number.');
if (settings.maxDistance !== undefined && !(isBoundedNumber(settings.maxDistance) && settings.maxDistance > 0)) throw surfaceError('raycast maxDistance must be above 0.');
const [partX, partY, partZ] = atParts(settings, state, depth, 'raycast', positionInput);
- const lookup = state.context.surfaceLookup;
+ const lookup = lookupOf(state.context);
if (!lookup) return VECTOR_READS.has(read) ? vectorValue(() => 0, () => 0, () => 0) : constantScalar(0);
const surfaceIndex = lookup.indexOf(surface);
const maxDistance = settings.maxDistance ?? Infinity;
@@ -127,3 +128,15 @@ export function compileRaycast(node, state, depth, positionInput) {
origin: [partX(index), partY(index), partZ(index)], direction, maxDistance, maxTriangleTests: remaining,
})), settings.miss);
}
+
+const lookups = new WeakMap();
+
+// One lookup per context, built on first use; a context without a loader (validation only) has none.
+function lookupOf(context) {
+ if (!context.loadSurface) return null;
+ if (!lookups.has(context)) lookups.set(context, createSurfaceLookup(context.loadSurface));
+ return lookups.get(context);
+}
+
+registerFieldSource('nearest', compileNearest);
+registerFieldSource('raycast', compileRaycast);
diff --git a/src/mesh-fields.js b/src/mesh-fields.js
index 92786fc7..687a3942 100644
--- a/src/mesh-fields.js
+++ b/src/mesh-fields.js
@@ -1,5 +1,4 @@
import { TAG_PREFIX, meshTags, vertexGroupWeights } from './mesh-data.js';
-import { compileNearest, compileRaycast, createSurfaceLookup } from './mesh-field-surfaces.js';
import { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK, FIELD_ATTRIBUTES } from './mesh-operations.js';
import { faceCentroids, faceNormals, vertexNormals } from './mesh-normals.js';
import {
@@ -161,6 +160,13 @@ OPERATORS.set('z', vectorOperator(1, 1, selectComponent(2)));
export { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK };
const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random', 'nearest', 'raycast']);
+
+// Inputs that other modules supply (the surface inputs register themselves), so a bundle that never reads one does not carry its code.
+const FIELD_SOURCES = new Map();
+
+export function registerFieldSource(name, compile) {
+ FIELD_SOURCES.set(name, compile);
+}
export const FIELD_OPERATORS = Object.freeze([...OPERATORS.keys(), ...SOURCE_KEYS]);
// ---------------------------------------------------------------------------------------------------------------
@@ -247,8 +253,8 @@ function compileInput(node, state, depth) {
if (keys[0] === 'noise') return compileNoise(node, state, depth);
if (keys[0] === 'random') return compileRandom(node);
const positionInput = () => compileAttribute({ attr: 'position' }, state.context);
- if (keys[0] === 'nearest') return compileNearest(node, state, depth, positionInput);
- if (keys[0] === 'raycast') return compileRaycast(node, state, depth, positionInput);
+ const compileSource = FIELD_SOURCES.get(keys[0]);
+ if (compileSource) return compileSource(node, state, depth, positionInput);
return undefined;
}
@@ -286,7 +292,7 @@ export function validateField(expression, { kind } = {}) {
}
const EMPTY = new Float64Array(0);
-const VALIDATION_CONTEXT = Object.freeze({ count: 0, positions: () => EMPTY, normals: () => EMPTY, tag: () => EMPTY, group: () => EMPTY, surfaceLookup: null });
+const VALIDATION_CONTEXT = Object.freeze({ count: 0, positions: () => EMPTY, normals: () => EMPTY, tag: () => EMPTY, group: () => EMPTY, loadSurface: null });
function finiteValues(source, count, width) {
const values = new Float64Array(count * width);
@@ -306,7 +312,7 @@ export function meshFieldContext(mesh, domain, loadSurface) {
count: isPoint ? mesh.vertexCount : mesh.faceCount,
positions: () => (cache.positions ??= isPoint ? mesh.positions : faceCentroids(mesh)),
normals: () => (cache.normals ??= isPoint ? vertexNormals(mesh) : faceNormals(mesh).normals),
- surfaceLookup: createSurfaceLookup(loadSurface),
+ loadSurface,
group: name => {
const weights = vertexGroupWeights(mesh, name);
return isPoint ? weights : faceGroupAverage(mesh, weights);
@@ -351,7 +357,7 @@ export function pointSetContext(positions, normals, loadSurface) {
count: positions.length / 3,
positions: () => positions,
normals: () => normals,
- surfaceLookup: createSurfaceLookup(loadSurface),
+ loadSurface,
group: name => {
throw new RangeError(`Unknown vertex group ${name}. Point sets carry no groups.`);
},
diff --git a/src/mesh-instances.js b/src/mesh-instances.js
index b711a7a4..f490dc20 100644
--- a/src/mesh-instances.js
+++ b/src/mesh-instances.js
@@ -2,6 +2,7 @@ import { quat } from 'gl-matrix';
import { INSTANCE_SOURCES, MAX_INSTANCE_CANDIDATES } from './mesh-operations.js';
import { evaluateField, pointSetContext, seededRandom } from './mesh-fields.js';
import { createTriangleSurfaceIndex } from './mesh-query.js';
+import './mesh-field-surfaces.js';
// Instance on points: a node with an `instances` record becomes a group node plus one child node per point, all
// sharing the node's geometry and material, so the renderer draws them in one instanced call. Points come from a
diff --git a/src/mesh-recipe.js b/src/mesh-recipe.js
index be6274e2..e8451959 100644
--- a/src/mesh-recipe.js
+++ b/src/mesh-recipe.js
@@ -22,6 +22,7 @@ import { sculptMesh, checkSculptBudget } from './mesh-sculpt.js';
import { shrinkwrapMesh } from './mesh-shrinkwrap.js';
import { triangulatedSurface } from './mesh-surface-distance.js';
import { createTriangleSurfaceIndex } from './mesh-query.js';
+import './mesh-field-surfaces.js';
import { remeshMesh, remeshGridSize, MAX_REMESH_RESOLUTION } from './mesh-remesh.js';
import {
MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES, SCULPT_STROKE_TYPES, MAX_SCULPT_STROKES, SHRINKWRAP_MODES,