Пример
three 0.185.1: InstancedMesh retains type 'Mesh' while identifying via isInstancedMesh, initializes instance matrices to identity, lazily allocates instanceColor with default white on first write, and maps raycast intersections to instanceId.
Проверенный пример — npm three 0.185.1: InstancedMesh retains type 'Mesh' while identifying via isInstancedMesh, initializes instance matrices to identity…
sha256:8454974a0cab4d93b0cf9ad4f2e64b2a4ada01e8766dc0f2ee4f94ae26108f9b
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 3
- Ключи подписи, собравшие его
- 3
Заявленная среда
node linux x64 node node npm
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-17 |
| node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-18 |
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-09-07 |
Кейс
HOW- Цель
- InstancedMesh retains type 'Mesh' while identifying via isInstancedMesh, initializes instance matrices to identity, lazily allocates instanceColor with default white on first write, and maps raycast intersections to instanceId.
- Пакеты
- Символы
-
- InstancedMesh
- Окружение
- node
- Создан
- 2026-08-17T09:07:02Z
Контракт
- InstancedMesh inherits type 'Mesh' while identifying via isInstancedMesh true, initializes all instance matrices to identity, and keeps instanceColor null until setColorAt is called.
- getColorAt returns default white RGB (1, 1, 1) without allocating instanceColor, while setColorAt initializes the entire buffer to white before setting the target index.
- computeBoundingBox computes the union of geometry bounds transformed by each instance matrix up to count.
- raycast automatically computes boundingSphere if null and populates each intersection with instanceId and the instanced mesh object reference.
- clone and ObjectLoader.parse retain instanceMatrix, instanceColor, and count.
Файлы
- NOTES.md
- csx.json
- package-lock.json
- package.json
- test/contract.mjs
Исходный код
# three: InstancedMesh
## Prior Verification Search
`search_known_solution` returned `NO_SAFE_MATCH` for `pkg:npm/three@0.185.1` exercising `InstancedMesh`.
## Pinned Release
- Package: `three`
- Exact Version: `0.185.1`
- Ecosystem: npm
## Observed Behavior
`InstancedMesh` extends `Mesh` to render many instances of the same geometry and material using GPU instancing.
1. **Type Property vs Instance Flag Trap**:
- Unlike `InstancedBufferGeometry` (which sets `type = 'InstancedBufferGeometry'`), `InstancedMesh` does not override `type` in its constructor; `mesh.type` remains `'Mesh'`.
- Applications checking `mesh.type === 'InstancedMesh'` will evaluate to `false` and take wrong code paths. Type discrimination must check `mesh.isInstancedMesh === true` or `mesh instanceof InstancedMesh`.
- However, `mesh.toJSON()` explicitly serializes `object.type = 'InstancedMesh'`, which `ObjectLoader` uses to branch into `new InstancedMesh(...)`.
2. **Instance Matrix Initialization**:
- `instanceMatrix` is an `InstancedBufferAttribute` of `Float32Array` with itemSize 16 and length `count * 16`.
- The constructor iterates over all `count` instances and sets each local matrix to the 4x4 identity matrix.
3. **Lazy Instance Color Allocation**:
- `instanceColor` defaults to `null` to conserve memory when per-instance tinting is unused.
- Calling `getColorAt(index, color)` when `instanceColor === null` sets the output color to full white RGB `(1, 1, 1)` without allocating memory.
- Calling `setColorAt(index, color)` lazily allocates `instanceColor` with all `count * 3` elements filled with `1.0` (white) before writing the targeted instance's RGB values.
4. **Bounding Volumes and Raycasting**:
- `boundingBox` and `boundingSphere` remain `null` until computed.
- `computeBoundingBox()` transforms the underlying geometry bounding box by each instance's transformation matrix up to `this.count` and unions the result.
- `raycast(raycaster, intersects)` automatically computes `boundingSphere` if null, checks the bounding sphere in world space, and tests each instance up to `this.count`. Each resulting intersection record has `intersect.instanceId` set to the integer instance index.
5. **Cloning and Deserialization**:
- `clone()` creates a new `InstancedMesh` retaining `isInstancedMesh = true`, `count`, `instanceMatrix`, and `instanceColor`.
- `ObjectLoader.prototype.parse()` reads `type: 'InstancedMesh'` and recreates the `InstancedMesh` with its matrices and colors.
{"case":{"believed":"InstancedMesh sets type to 'InstancedMesh', initializes instanceColor to an allocated buffer on construction, and requires manual bounding sphere computation before raycasting.","caseId":"case:sha256:1afbf74d47f6f36df9095115d1b21f1947148a8ec9d67cc7e1b1c05aeffd92e8","contract":["InstancedMesh inherits type 'Mesh' while identifying via isInstancedMesh true, initializes all instance matrices to identity, and keeps instanceColor null until setColorAt is called.","getColorAt returns default white RGB (1, 1, 1) without allocating instanceColor, while setColorAt initializes the entire buffer to white before setting the target index.","computeBoundingBox computes the union of geometry bounds transformed by each instance matrix up to count.","raycast automatically computes boundingSphere if null and populates each intersection with instanceId and the instanced mesh object reference.","clone and ObjectLoader.parse retain instanceMatrix, instanceColor, and count."],"goal":"InstancedMesh retains type 'Mesh' while identifying via isInstancedMesh, initializes instance matrices to identity, lazily allocates instanceColor with default white on first write, and maps raycast intersections to instanceId.","kind":"HOW","packages":["pkg:npm/three@0.185.1"],"schemaVersion":1,"symbols":["InstancedMesh"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/three@0.185.1"],"schemaVersion":1,"symbols":["InstancedMesh"],"verifierAdapter":"node-typescript@1"}
{
"name": "npm-three-wanted-0-185-1-instancedmesh-9814e873f916433ab4d7dbe2",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "npm-three-wanted-0-185-1-instancedmesh-9814e873f916433ab4d7dbe2",
"version": "1.0.0",
"dependencies": {
"three": "0.185.1"
}
},
"node_modules/three": {
"version": "0.185.1",
"resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz",
"integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==",
"license": "MIT"
}
}
}
{
"name": "npm-three-wanted-0-185-1-instancedmesh-9814e873f916433ab4d7dbe2",
"version": "1.0.0",
"description": "CodeSampleX sample for three.js InstancedMesh",
"type": "module",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"three": "0.185.1"
}
}
import assert from 'node:assert/strict';
import {
InstancedMesh,
BoxGeometry,
MeshBasicMaterial,
Matrix4,
Color,
Raycaster,
Vector3,
ObjectLoader,
InstancedBufferAttribute,
} from 'three';
// 1. Instantiation, identity matrices, and type properties
const geometry = new BoxGeometry(1, 1, 1);
const material = new MeshBasicMaterial();
const count = 3;
const mesh = new InstancedMesh(geometry, material, count);
// InstancedMesh identifies with isInstancedMesh = true, but its type property remains 'Mesh'
assert.strictEqual(mesh.isInstancedMesh, true);
assert.strictEqual(mesh.type, 'Mesh');
assert.strictEqual(mesh.count, 3);
// instanceMatrix is an InstancedBufferAttribute with itemSize 16 and length count * 16
assert.ok(mesh.instanceMatrix instanceof InstancedBufferAttribute);
assert.strictEqual(mesh.instanceMatrix.itemSize, 16);
assert.strictEqual(mesh.instanceMatrix.count, 3);
assert.strictEqual(mesh.instanceMatrix.array.length, 48);
// All matrices are initialized to 4x4 identity matrices by default in the constructor
const matrix = new Matrix4();
for (let i = 0; i < count; i++) {
mesh.getMatrixAt(i, matrix);
assert.deepStrictEqual(
Array.from(matrix.elements),
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
);
}
// 2. instanceColor lazy initialization and getColorAt / setColorAt behavior
// Initially, instanceColor is null
assert.strictEqual(mesh.instanceColor, null);
// getColorAt does not allocate instanceColor; it writes default white (1, 1, 1) into target color
const color = new Color();
mesh.getColorAt(0, color);
assert.strictEqual(color.r, 1);
assert.strictEqual(color.g, 1);
assert.strictEqual(color.b, 1);
assert.strictEqual(mesh.instanceColor, null);
// setColorAt lazily allocates instanceColor filled with 1.0 (white) for all instances,
// then sets the requested instance's RGB
mesh.setColorAt(1, new Color(1, 0, 0)); // set instance 1 to red
assert.ok(mesh.instanceColor instanceof InstancedBufferAttribute);
assert.strictEqual(mesh.instanceColor.itemSize, 3);
assert.strictEqual(mesh.instanceColor.count, 3);
assert.strictEqual(mesh.instanceColor.array.length, 9);
// Instance 0 remains default white (1, 1, 1) in the newly allocated buffer
mesh.getColorAt(0, color);
assert.strictEqual(color.r, 1);
assert.strictEqual(color.g, 1);
assert.strictEqual(color.b, 1);
// Instance 1 is red (1, 0, 0)
mesh.getColorAt(1, color);
assert.strictEqual(color.r, 1);
assert.strictEqual(color.g, 0);
assert.strictEqual(color.b, 0);
// 3. Transformations and computeBoundingBox / computeBoundingSphere
// Position instances at x = 0, x = 10, x = 20
mesh.setMatrixAt(0, new Matrix4().makeTranslation(0, 0, 0));
mesh.setMatrixAt(1, new Matrix4().makeTranslation(10, 0, 0));
mesh.setMatrixAt(2, new Matrix4().makeTranslation(20, 0, 0));
// Bounding box is null until explicitly computed
assert.strictEqual(mesh.boundingBox, null);
mesh.computeBoundingBox();
assert.ok(mesh.boundingBox !== null);
// BoxGeometry(1, 1, 1) centered at origin spans [-0.5, 0.5] along each axis
assert.strictEqual(mesh.boundingBox.min.x, -0.5);
assert.strictEqual(mesh.boundingBox.min.y, -0.5);
assert.strictEqual(mesh.boundingBox.min.z, -0.5);
assert.strictEqual(mesh.boundingBox.max.x, 20.5);
assert.strictEqual(mesh.boundingBox.max.y, 0.5);
assert.strictEqual(mesh.boundingBox.max.z, 0.5);
// 4. Raycasting against individual instances
// boundingSphere is null before raycast; raycast computes it automatically if null
assert.strictEqual(mesh.boundingSphere, null);
const raycaster = new Raycaster(new Vector3(10, 0, 5), new Vector3(0, 0, -1));
const intersects = [];
mesh.raycast(raycaster, intersects);
assert.ok(mesh.boundingSphere !== null);
assert.strictEqual(intersects.length, 2); // front and back faces of the box
assert.strictEqual(intersects[0].instanceId, 1);
assert.strictEqual(intersects[0].object, mesh);
assert.strictEqual(intersects[1].instanceId, 1);
// 5. Cloning
const cloned = mesh.clone();
assert.strictEqual(cloned.isInstancedMesh, true);
assert.strictEqual(cloned.type, 'Mesh');
assert.strictEqual(cloned.count, 3);
assert.strictEqual(cloned.instanceMatrix.count, 3);
assert.strictEqual(cloned.instanceColor.count, 3);
const clonedMatrix = new Matrix4();
cloned.getMatrixAt(2, clonedMatrix);
assert.strictEqual(clonedMatrix.elements[12], 20);
const clonedColor = new Color();
cloned.getColorAt(1, clonedColor);
assert.strictEqual(clonedColor.r, 1);
assert.strictEqual(clonedColor.g, 0);
assert.strictEqual(clonedColor.b, 0);
// 6. Serialization toJSON and Deserialization via ObjectLoader
const json = mesh.toJSON();
assert.strictEqual(json.object.type, 'InstancedMesh');
assert.strictEqual(json.object.count, 3);
assert.ok(json.object.instanceMatrix !== undefined);
assert.ok(json.object.instanceColor !== undefined);
const loader = new ObjectLoader();
const parsed = loader.parse(json);
assert.strictEqual(parsed.isInstancedMesh, true);
assert.strictEqual(parsed.type, 'Mesh');
assert.strictEqual(parsed.count, 3);
assert.strictEqual(parsed.instanceMatrix.count, 3);
assert.strictEqual(parsed.instanceColor.count, 3);
const parsedMatrix = new Matrix4();
parsed.getMatrixAt(2, parsedMatrix);
assert.strictEqual(parsedMatrix.elements[12], 20);
const parsedColor = new Color();
parsed.getColorAt(1, parsedColor);
assert.strictEqual(parsedColor.r, 1);
assert.strictEqual(parsedColor.g, 0);
assert.strictEqual(parsedColor.b, 0);
console.log('Contract passed successfully.');