@volter/blender-engine 0.1.74 → 0.1.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,11 @@ import type {MotionMeshRequest, MotionMeshResponse} from './blender-motion-worke
4
4
 
5
5
  const CACHE_BYTES = 64 * 1024 * 1024;
6
6
  const QUIET_MS = 150;
7
+ // At most 16,384 triangles are copied/simplified in a single worker request.
8
+ const CHUNK_INDICES = 49_152;
9
+ const COPY_ITEMS = 8_192;
10
+ const cancelled = Symbol('navigation geometry replaced');
11
+ type Range = {start: number; count: number; materialIndex?: number | undefined};
7
12
  type Entry = {geometry: THREE.BufferGeometry; error: number; bytes: number};
8
13
 
9
14
  /** A disposable navigation drawing, never Blender's evaluated geometry.
@@ -15,13 +20,16 @@ export class BlenderMotionGeometry {
15
20
  private readonly swapped: {mesh: THREE.Mesh; geometry: THREE.BufferGeometry}[] = [];
16
21
  private queue: THREE.BufferGeometry[] = [];
17
22
  private worker: Worker | null = null;
18
- private pending: {id: number; geometry: THREE.BufferGeometry} | null = null;
23
+ private pending: {id: number; resolve: (response: MotionMeshResponse) => void} | null = null;
24
+ private generation = 0;
25
+ private building = false;
19
26
  private nextId = 0;
20
27
  private signature = '';
21
28
  private readonly identities = new WeakMap<object, number>();
22
29
  private nextIdentity = 0;
23
30
  private bytes = 0;
24
31
  private unavailable: string | null = null;
32
+ private reductions: {vertices: number; fullTriangles: number; reducedTriangles: number; error: number; accepted: boolean}[] = [];
25
33
  private timer: ReturnType<typeof setTimeout> | null = null;
26
34
  private readonly cameraWorld = new THREE.Matrix4();
27
35
  private readonly cameraProjection = new THREE.Matrix4();
@@ -45,15 +53,22 @@ export class BlenderMotionGeometry {
45
53
  (mesh as THREE.InstancedMesh).isInstancedMesh || mesh.morphTargetInfluences) continue;
46
54
  const g = mesh.geometry;
47
55
  const position = g.getAttribute('position');
48
- if (!g.index || g.index.count < 6144 || !position || position.count > 200_000 ||
56
+ if (!g.index || g.index.count < 6144 || !position || position.count > 8_000_000 ||
49
57
  Object.values(g.attributes).some(a => !(a instanceof THREE.BufferAttribute) ||
50
58
  (a as THREE.BufferAttribute & {isFloat16BufferAttribute?: boolean}).isFloat16BufferAttribute ||
51
59
  (a as THREE.InstancedBufferAttribute).isInstancedBufferAttribute) ||
52
60
  Object.keys(g.morphAttributes).length || g.drawRange.start !== 0 || g.drawRange.count < g.index.count) continue;
53
- // Only a whole, single material surface. Material boundaries are never
54
- // crossed by the simplifier, nor are authored group ranges shortened.
55
- if (Array.isArray(mesh.material) && (mesh.material.length !== 1 || g.groups.length !== 1 ||
56
- g.groups[0]!.start !== 0 || g.groups[0]!.count !== g.index.count || g.groups[0]!.materialIndex !== 0)) continue;
61
+ // Support ordered, disjoint material ranges. Overlaps/gaps or a shared
62
+ // geometry interpreted differently by two objects retain full detail.
63
+ if (Array.isArray(mesh.material)) {
64
+ let end = 0;
65
+ if (!g.groups.length || g.groups.some(range => {
66
+ const valid = range.start === end && range.count > 0 && range.count % 3 === 0 &&
67
+ Number.isInteger(range.materialIndex) && range.materialIndex! >= 0 && range.materialIndex! < (mesh.material as THREE.Material[]).length;
68
+ end = range.start + range.count;
69
+ return !valid;
70
+ }) || end !== g.index.count) continue;
71
+ }
57
72
  const held = groups.get(g);
58
73
  if (held) held.push(mesh); else groups.set(g, [mesh]);
59
74
  }
@@ -63,7 +78,7 @@ export class BlenderMotionGeometry {
63
78
  if (id === undefined) { id = ++this.nextIdentity; this.identities.set(object, id); }
64
79
  return id;
65
80
  };
66
- const signature = [...groups].map(([g]) => `${g.id}:${identity(g.index!)}:${g.index!.version}:` +
81
+ const signature = [...groups].map(([g, meshes]) => `${g.id}:${identity(g.index!)}:${g.index!.version}:${Array.isArray(meshes[0]!.material)}:${JSON.stringify(g.groups)}:` +
67
82
  Object.entries(g.attributes).map(([name, a]) => `${name}:${identity(a)}:${(a as THREE.BufferAttribute).version}`).join(',')).join(';');
68
83
  if (signature === this.signature) return;
69
84
  this.releaseCopies();
@@ -78,95 +93,159 @@ export class BlenderMotionGeometry {
78
93
  this.next();
79
94
  }
80
95
 
81
- private next(): void {
82
- if (this.pending || this.unavailable || this.bytes >= CACHE_BYTES) return;
96
+ private async next(): Promise<void> {
97
+ if (this.building || this.unavailable || this.bytes >= CACHE_BYTES) return;
83
98
  const geometry = this.queue.shift();
84
99
  if (!geometry) { this.worker?.terminate(); this.worker = null; return; }
85
- if (!this.worker) {
86
- try {
100
+ this.building = true;
101
+ const generation = this.generation;
102
+ const current = () => {
103
+ if (generation !== this.generation) throw cancelled;
104
+ if (this.unavailable) throw new Error(this.unavailable);
105
+ };
106
+ const yieldCopy = async () => { await new Promise<void>(resolve => setTimeout(resolve, 0)); current(); };
107
+ try {
108
+ if (!this.worker) {
87
109
  this.worker = new Worker(new URL('./blender-motion-worker.ts', import.meta.url), {type: 'module'});
88
- this.worker.onmessage = (event: MessageEvent<MotionMeshResponse>) => this.receive(event.data);
110
+ this.worker.onmessage = (event: MessageEvent<MotionMeshResponse>) => {
111
+ if (this.pending?.id === event.data.id) {
112
+ const pending = this.pending; this.pending = null; pending.resolve(event.data);
113
+ }
114
+ };
89
115
  this.worker.onerror = event => {
90
116
  this.unavailable = event.message || 'Navigation geometry worker unavailable';
91
- this.worker?.terminate(); this.worker = null; this.pending = null;
92
- this.queue.length = 0;
117
+ this.worker?.terminate(); this.worker = null;
118
+ const pending = this.pending; this.pending = null;
119
+ pending?.resolve({id: pending.id, refusal: this.unavailable});
93
120
  };
94
- } catch (error) {
95
- // This is an optional presentation. Refusal retains full geometry,
96
- // with a visible diagnostic; never fall back to blocking the UI.
97
- this.unavailable = String(error); return;
98
121
  }
99
- }
100
- const position = geometry.getAttribute('position') as THREE.BufferAttribute;
101
- const positions = new Float32Array(position.count * 3);
102
- for (let i = 0; i < position.count; i++) {
103
- positions[i * 3] = position.getX(i); positions[i * 3 + 1] = position.getY(i); positions[i * 3 + 2] = position.getZ(i);
104
- }
105
- // Normals and UVs contribute appearance error. All attributes, including
106
- // those not used to rank collapses, are retained in the resulting copy.
107
- const attributes = Object.entries(geometry.attributes).filter(([name]) => name === 'normal' || /^uv\d*$/.test(name));
108
- const stride = attributes.reduce((n, [, a]) => n + a.itemSize, 0);
109
- const values = new Float32Array(position.count * stride);
110
- const weights: number[] = [];
111
- let offset = 0;
112
- for (const [name, a] of attributes) {
113
- for (let c = 0; c < a.itemSize; c++) weights.push(name === 'normal' ? 0.5 : 1);
114
- for (let i = 0; i < position.count; i++) for (let c = 0; c < a.itemSize; c++)
115
- values[i * stride + offset + c] = (a as THREE.BufferAttribute).getComponent(i, c);
116
- offset += a.itemSize;
117
- }
118
- const indices = new Uint32Array(geometry.index!.array);
119
- const id = ++this.nextId;
120
- this.pending = {id, geometry};
121
- const request: MotionMeshRequest = {id, positions, indices, attributes: values, stride, weights};
122
- this.worker.postMessage(request, [positions.buffer, indices.buffer, values.buffer]);
123
- }
124
-
125
- private receive(response: MotionMeshResponse): void {
126
- const pending = this.pending;
127
- if (!pending || pending.id !== response.id) return;
128
- this.pending = null;
129
- const {geometry} = pending;
130
- const indices = response.indices;
131
- if (response.refusal) {
132
- this.unavailable = response.refusal;
133
- this.worker?.terminate(); this.worker = null; this.queue.length = 0;
134
- }
135
- if (indices && response.error !== undefined && Number.isFinite(response.error) &&
136
- indices.length > 0 && indices.length < geometry.index!.count * 0.75) {
122
+ const position = geometry.getAttribute('position') as THREE.BufferAttribute;
123
+ const meshes = this.groups.get(geometry)!;
124
+ const multi = Array.isArray(meshes[0]!.material);
125
+ if (meshes.some(mesh => Array.isArray(mesh.material) !== multi)) return;
126
+ const ranges: Range[] = multi ? geometry.groups : [{start: 0, count: geometry.index!.count}];
127
+ const appearance = Object.entries(geometry.attributes).filter(([name]) => name === 'normal' || /^uv\d*$/.test(name));
128
+ const stride = appearance.reduce((n, [, a]) => n + a.itemSize, 0);
129
+ const weights = appearance.flatMap(([name, a]) => Array(a.itemSize).fill(name === 'normal' ? 0.5 : 1));
130
+ // Reuse bounds when present, otherwise derive the error scale in
131
+ // yielding slices. Never scan a large mesh in one UI-thread call.
132
+ const bounds = geometry.boundingBox?.clone() ?? new THREE.Box3();
133
+ if (!geometry.boundingBox) {
134
+ const point = new THREE.Vector3();
135
+ for (let first = 0; first < position.count; first += COPY_ITEMS) {
136
+ await yieldCopy();
137
+ for (let i = first; i < Math.min(first + COPY_ITEMS, position.count); i++)
138
+ bounds.expandByPoint(point.fromBufferAttribute(position, i));
139
+ }
140
+ }
141
+ if (!geometry.boundingSphere) return;
142
+ const absoluteError = Math.max(bounds.max.x - bounds.min.x, bounds.max.y - bounds.min.y,
143
+ bounds.max.z - bounds.min.z) * 0.002;
144
+ const parts: Uint32Array[] = [];
145
+ const outputGroups: Range[] = [];
146
+ let count = 0, error = 0;
147
+ for (const range of ranges) {
148
+ const groupStart = count;
149
+ for (let start = range.start; start < range.start + range.count; start += CHUNK_INDICES) {
150
+ await yieldCopy();
151
+ const end = Math.min(start + CHUNK_INDICES, range.start + range.count);
152
+ const originals: number[] = [], remap = new Map<number, number>();
153
+ const indices = new Uint32Array(end - start);
154
+ for (let i = start; i < end; i++) {
155
+ const original = geometry.index!.getX(i);
156
+ let local = remap.get(original);
157
+ if (local === undefined) { local = originals.length; originals.push(original); remap.set(original, local); }
158
+ indices[i - start] = local;
159
+ }
160
+ const positions = new Float32Array(originals.length * 3);
161
+ const values = new Float32Array(originals.length * stride);
162
+ for (let first = 0; first < originals.length; first += COPY_ITEMS) {
163
+ await yieldCopy();
164
+ for (let i = first; i < Math.min(first + COPY_ITEMS, originals.length); i++) {
165
+ const original = originals[i]!;
166
+ for (let c = 0; c < 3; c++) positions[i * 3 + c] = position.getComponent(original, c);
167
+ let offset = 0;
168
+ for (const [, attribute] of appearance) {
169
+ for (let c = 0; c < attribute.itemSize; c++)
170
+ values[i * stride + offset + c] = (attribute as THREE.BufferAttribute).getComponent(original, c);
171
+ offset += attribute.itemSize;
172
+ }
173
+ }
174
+ }
175
+ const id = ++this.nextId;
176
+ const response = await new Promise<MotionMeshResponse>(resolve => {
177
+ this.pending = {id, resolve};
178
+ const request: MotionMeshRequest = {id, positions, indices, attributes: values, stride, weights, absoluteError};
179
+ this.worker!.postMessage(request, [positions.buffer, indices.buffer, values.buffer]);
180
+ });
181
+ current();
182
+ if (response.refusal) throw new Error(response.refusal);
183
+ if (!response.indices || !Number.isFinite(response.error)) throw new Error('Invalid navigation geometry response');
184
+ const reduced = response.indices;
185
+ for (let i = 0; i < reduced.length; i++) reduced[i] = originals[reduced[i]!]!;
186
+ count += reduced.length;
187
+ if (count * 4 > CACHE_BYTES - this.bytes) return;
188
+ parts.push(reduced);
189
+ error = Math.max(error, response.error!);
190
+ }
191
+ if (multi) outputGroups.push({start: groupStart, count: count - groupStart, materialIndex: range.materialIndex});
192
+ }
193
+ const reduction = {vertices: position.count, fullTriangles: geometry.index!.count / 3,
194
+ reducedTriangles: count / 3, error, accepted: false};
195
+ if (this.reductions.length < 32) this.reductions.push(reduction);
196
+ if (!count || count >= geometry.index!.count * 0.75) return;
197
+ // Compact only after all material ranges succeed. Yield while remapping
198
+ // and copying; cancellation never publishes a partial surface.
199
+ const remap = new Int32Array(position.count).fill(-1);
137
200
  const originals: number[] = [];
138
- const remap = new Map<number, number>();
139
- for (let i = 0; i < indices.length; i++) {
140
- const original = indices[i]!;
141
- let index = remap.get(original);
142
- if (index === undefined) { index = originals.length; originals.push(original); remap.set(original, index); }
143
- indices[i] = index;
201
+ const indices = new Uint32Array(count);
202
+ let offset = 0;
203
+ for (const part of parts) {
204
+ for (let first = 0; first < part.length; first += COPY_ITEMS) {
205
+ await yieldCopy();
206
+ for (let i = first; i < Math.min(first + COPY_ITEMS, part.length); i++) {
207
+ const original = part[i]!;
208
+ let local = remap[original]!;
209
+ if (local < 0) { local = originals.length; originals.push(original); remap[original] = local; }
210
+ indices[offset + i] = local;
211
+ }
212
+ }
213
+ offset += part.length;
144
214
  }
145
215
  const bytes = indices.byteLength + Object.values(geometry.attributes).reduce((n, a) =>
146
216
  n + originals.length * a.itemSize * a.array.BYTES_PER_ELEMENT, 0);
147
- if (this.bytes + bytes <= CACHE_BYTES) {
148
- const copy = new THREE.BufferGeometry();
149
- copy.setIndex(new THREE.BufferAttribute(indices, 1));
150
- for (const [name, source] of Object.entries(geometry.attributes)) {
151
- const attribute = source as THREE.BufferAttribute;
152
- const ArrayType = attribute.array.constructor as {new(length: number): THREE.TypedArray};
153
- const data = new ArrayType(originals.length * attribute.itemSize);
154
- for (let i = 0; i < originals.length; i++) for (let c = 0; c < attribute.itemSize; c++)
155
- data[i * attribute.itemSize + c] = attribute.array[originals[i]! * attribute.itemSize + c]!;
156
- copy.setAttribute(name, new THREE.BufferAttribute(data, attribute.itemSize, attribute.normalized));
217
+ if (this.bytes + bytes > CACHE_BYTES) return;
218
+ const copy = new THREE.BufferGeometry();
219
+ copy.setIndex(new THREE.BufferAttribute(indices, 1));
220
+ for (const [name, source] of Object.entries(geometry.attributes)) {
221
+ const attribute = source as THREE.BufferAttribute;
222
+ const ArrayType = attribute.array.constructor as {new(length: number): THREE.TypedArray};
223
+ const data = new ArrayType(originals.length * attribute.itemSize);
224
+ for (let first = 0; first < originals.length; first += COPY_ITEMS) {
225
+ await yieldCopy();
226
+ for (let i = first; i < Math.min(first + COPY_ITEMS, originals.length); i++)
227
+ for (let c = 0; c < attribute.itemSize; c++)
228
+ data[i * attribute.itemSize + c] = attribute.array[originals[i]! * attribute.itemSize + c]!;
157
229
  }
158
- // Retain the exact culling/sorting bounds and material assignment.
159
- if (!geometry.boundingSphere) geometry.computeBoundingSphere();
160
- copy.boundingSphere = geometry.boundingSphere!.clone();
161
- copy.boundingBox = geometry.boundingBox?.clone() ?? null;
162
- if (geometry.groups.length === 1) copy.addGroup(0, indices.length, geometry.groups[0]!.materialIndex);
163
- copy.userData = {...geometry.userData};
164
- this.cache.set(geometry, {geometry: copy, error: response.error, bytes});
165
- this.bytes += bytes;
230
+ copy.setAttribute(name, new THREE.BufferAttribute(data, attribute.itemSize, attribute.normalized));
231
+ }
232
+ copy.boundingSphere = geometry.boundingSphere.clone();
233
+ copy.boundingBox = bounds.clone();
234
+ for (const group of outputGroups) copy.addGroup(group.start, group.count, group.materialIndex);
235
+ copy.userData = {...geometry.userData};
236
+ reduction.accepted = true;
237
+ this.cache.set(geometry, {geometry: copy, error, bytes});
238
+ this.bytes += bytes;
239
+ } catch (error) {
240
+ if (error === cancelled) return;
241
+ this.unavailable = String(error);
242
+ this.worker?.terminate(); this.worker = null; this.pending = null; this.queue.length = 0;
243
+ } finally {
244
+ if (generation === this.generation) {
245
+ this.building = false;
246
+ this.timer = setTimeout(() => { this.timer = null; void this.next(); }, 0);
166
247
  }
167
248
  }
168
- // Yield between meshes, including copying their attributes for the worker.
169
- this.timer = setTimeout(() => { this.timer = null; this.next(); }, 0);
170
249
  }
171
250
 
172
251
  prepare(camera: THREE.Camera, interactive: boolean, height: number): boolean {
@@ -224,16 +303,19 @@ export class BlenderMotionGeometry {
224
303
  this.swapped.length = 0;
225
304
  }
226
305
  inspect() {
227
- return {copies: this.cache.size, bytes: this.bytes, queued: this.queue.length, pending: this.pending !== null,
228
- unavailable: this.unavailable, lastNavigation: {...this.lastNavigation}};
306
+ return {copies: this.cache.size, bytes: this.bytes, queued: this.queue.length, pending: this.building,
307
+ unavailable: this.unavailable, reductions: this.reductions.map(r => ({...r})), lastNavigation: {...this.lastNavigation}};
229
308
  }
230
309
  private releaseCopies(): void {
231
310
  this.finish();
232
311
  if (this.timer) clearTimeout(this.timer);
233
312
  this.timer = null;
234
- this.worker?.terminate(); this.worker = null; this.pending = null; this.queue = [];
313
+ this.generation++;
314
+ this.worker?.terminate(); this.worker = null;
315
+ this.pending?.resolve({id: this.pending.id, refusal: 'Navigation geometry replaced'});
316
+ this.pending = null; this.building = false; this.queue = [];
235
317
  for (const entry of this.cache.values()) entry.geometry.dispose();
236
- this.cache.clear(); this.bytes = 0;
318
+ this.cache.clear(); this.bytes = 0; this.reductions = [];
237
319
  }
238
320
  clear(): void {
239
321
  this.releaseCopies();
@@ -7,24 +7,25 @@ export interface MotionMeshRequest {
7
7
  attributes: Float32Array;
8
8
  stride: number;
9
9
  weights: number[];
10
+ absoluteError: number;
10
11
  }
11
12
  export interface MotionMeshResponse {id: number; indices?: Uint32Array; error?: number; refusal?: string}
12
13
 
13
14
  // One copied mesh at a time. The worker never owns or detaches a resident
14
15
  // Blender column, and never writes positions or attributes back to the model.
15
16
  self.onmessage = async (event: MessageEvent<MotionMeshRequest>) => {
16
- const {id, positions, indices, attributes, stride, weights} = event.data;
17
+ const {id, positions, indices, attributes, stride, weights, absoluteError} = event.data;
17
18
  try {
18
19
  await MeshoptSimplifier.ready;
19
20
  const target = Math.max(384, Math.floor(indices.length * 0.08 / 3) * 3);
20
21
  const [reduced, error] = MeshoptSimplifier.simplifyWithAttributes(
21
- indices, positions, 3, attributes, stride, weights, null, target, 0.002,
22
+ indices, positions, 3, attributes, stride, weights, null, target, absoluteError,
22
23
  // Preserve open boundaries and attribute seams. If that prevents a
23
24
  // useful reduction, keep the original; never sample/drop triangles.
24
- ['LockBorder'],
25
+ ['LockBorder', 'ErrorAbsolute'],
25
26
  );
26
27
  const response: MotionMeshResponse = {
27
- id, indices: reduced, error: error * MeshoptSimplifier.getScale(positions, 3),
28
+ id, indices: reduced, error,
28
29
  };
29
30
  self.postMessage(response, {transfer: [reduced.buffer]});
30
31
  } catch (error) {
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@volter/blender-engine",
3
3
  "author": "Volter AI, Inc.",
4
4
  "license": "GPL-3.0-or-later",
5
- "version": "0.1.74",
5
+ "version": "0.1.75",
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },