@inneranimalmedia/agentsam-3d-viewer 0.0.0-stage → 2.6.15

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.
package/LICENSE ADDED
@@ -0,0 +1,110 @@
1
+ # Functional Source License, Version 1.1, MIT Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-MIT
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 Sam Primeaux, d/b/a Inner Animal Media
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the MIT license that is effective on the second anniversary of the date we make
91
+ the Software available. On or after that date, you may use the Software under
92
+ the MIT license, in which case the following will apply:
93
+
94
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
95
+ this software and associated documentation files (the "Software"), to deal in
96
+ the Software without restriction, including without limitation the rights to
97
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
98
+ of the Software, and to permit persons to whom the Software is furnished to do
99
+ so, subject to the following conditions:
100
+
101
+ The above copyright notice and this permission notice shall be included in all
102
+ copies or substantial portions of the Software.
103
+
104
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
105
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
106
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
107
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
108
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
109
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
110
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # `@inneranimalmedia/agentsam-3d-viewer`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A reusable rendering and native-CAD mesh-display capability for any AgentSam product or public site. It does not create geometry and does not initialize OCCT; verified native C++ OCCT B-rep solids remain authoritative in the CAD engine. Use it to display existing GLB, GLTF, or STL assets with responsive sizing, orbit controls, camera fitting, accessible loading/error status, and deterministic disposal.
4
+
5
+ ## Mount an existing model
6
+
7
+ ```ts
8
+ import * as THREE from 'three';
9
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
10
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
11
+ import { STLLoader } from 'three/addons/loaders/STLLoader.js';
12
+ import { mountModelViewer } from '@inneranimalmedia/agentsam-3d-viewer';
13
+
14
+ const runtime = { THREE, OrbitControls, GLTFLoader, STLLoader };
15
+ const viewer = mountModelViewer(document.querySelector('#model-preview')!, '/models/house.glb', runtime, {
16
+ ariaLabel: 'Interactive house model',
17
+ background: '#111722',
18
+ showGrid: true,
19
+ autoRotate: false,
20
+ });
21
+
22
+ await viewer.ready;
23
+ // On route change / component unmount:
24
+ viewer.dispose();
25
+ ```
26
+
27
+ The host supplies its existing Three.js runtime so the package does not bundle a second Three.js copy. Consumers must have Three.js installed and pass the `THREE` namespace plus the loaders/controls they use.
28
+
29
+ Use `createThreeViewport(container, runtime, { autoRender: false })` when a product needs its own scene graph, picking, visibility/isolating, or render loop. The returned viewport exposes the scene, camera, renderer, orbit controls, `fit(object)`, `render()`, and `dispose()` so CAD-specific behavior remains in the host rather than being forced into a generic viewer.
30
+
31
+ The package reads GLB/GLTF/STL. Precision geometry, Boolean operations, and STEP authoring belong to `@inneranimalmedia/agentsam-occt`; viewer and engine remain separate so marketing pages can display a model without loading the OCCT WebAssembly kernel.
32
+
33
+ This package is designed for standalone npm distribution as `@inneranimalmedia/agentsam-3d-viewer`. The repository remains the canonical source and the host provides its own Three.js runtime.
34
+
35
+ ## Shared engineering viewport (v0.2)
36
+
37
+ Use `createThreeViewport(container, { THREE }, { controls: false, autoRender: false, wrapper: false })`
38
+ when the host owns camera navigation, as DreamHouse orbit/walk and CAD Model do.
39
+ The returned camera, scene and WebGL renderer use the common GPU lifecycle,
40
+ resize observer, color space and cleanup. Do not create another WebGLRenderer
41
+ inside those hosts; custom camera controls and CAD object picking stay in the host.
42
+
43
+ Use `createOcctMeshGeometry(nativeMesh, { THREE })` (or the `/occt` subpath)
44
+ for a **display mesh produced by the verified C++ OCCT engine**. It checks
45
+ `units: mm`, `axes: z-up`, indices and finite vertex data, maps the result into
46
+ Three.js meter / Y-up coordinates and preserves the native data unchanged.
47
+ It never turns arbitrary triangle soup into an exact CAD solid.
48
+
49
+ Integration receipts:
50
+ - SamSketch: `apps/samsketch/src/main.ts`
51
+ - CAD model: `apps/cad-creator/frontend/src/components/Viewport3D.tsx`
52
+ - DreamHouse world: `apps/cad-creator/frontend/src/components/DreamHouseWorldViewport.tsx`
53
+ - Native geometry: `apps/cad-creator/frontend/src/lib/native-mesh-three.ts`
54
+
55
+ Robotics `RenderSystem` now uses this shared viewport lifecycle with Z-up
56
+ camera initialization; robot motion/physics and transform controls stay in
57
+ robotics. Next work is consolidating scene picking, section planes and BIM
58
+ inspection extensions. The viewer does **not** execute a C++ kernel in-browser.
@@ -0,0 +1,63 @@
1
+ {
2
+ "schema": "agentsam.package.v1",
3
+ "id": "agentsam-3d-viewer",
4
+ "name": "@inneranimalmedia/agentsam-3d-viewer",
5
+ "version": "0.2.0",
6
+ "class": "package",
7
+ "status": "in-development",
8
+ "catalog_status": "needs-review",
9
+ "languages": [
10
+ "javascript",
11
+ "typescript"
12
+ ],
13
+ "execution_domains": [
14
+ "browser",
15
+ "desktop"
16
+ ],
17
+ "purpose": "Shared framework-agnostic Three.js viewport, model viewing, and verified OCCT mesh display adapters for BIM, robotics and public scenes; native OCCT stays geometry authority.",
18
+ "install": [
19
+ {
20
+ "type": "npm-workspace",
21
+ "package": "@inneranimalmedia/agentsam-3d-viewer",
22
+ "command": "npm install --workspace @inneranimalmedia/agentsam-3d-viewer"
23
+ }
24
+ ],
25
+ "registry": {
26
+ "kind": "npm-workspace",
27
+ "name": "@inneranimalmedia/agentsam-3d-viewer",
28
+ "public_claim": false
29
+ },
30
+ "use_when": [
31
+ "Showing an existing GLB, GLTF, or STL in a public marketing page or application panel",
32
+ "Creating a reusable Three.js viewport while keeping CAD-specific selection and scene logic in the host",
33
+ "Displaying validated native OCCT tessellations with consistent units, axes and indexed triangles"
34
+ ],
35
+ "avoid_when": [
36
+ "Generating precision solids or Boolean geometry; use agentsam-occt",
37
+ "Replacing specialized BIM, robotics, or scene-authoring behavior with a generic asset viewer"
38
+ ],
39
+ "commands": [],
40
+ "topics": [
41
+ "3d",
42
+ "threejs",
43
+ "glb",
44
+ "gltf",
45
+ "stl",
46
+ "viewer",
47
+ "visualization"
48
+ ],
49
+ "evidence": {
50
+ "directory": "packages/agentsam-3d-viewer",
51
+ "tests": [
52
+ "packages/agentsam-3d-viewer/test/format.test.mjs",
53
+ "packages/agentsam-3d-viewer/test/viewport.test.mjs"
54
+ ],
55
+ "consumers": [
56
+ "apps/samsketch/src/main.ts",
57
+ "apps/cad-creator/frontend/src/components/DreamHouseWorldViewport.tsx",
58
+ "apps/cad-creator/frontend/src/lib/native-mesh-three.ts",
59
+ "apps/cad-creator/frontend/src/components/Viewport3D.tsx",
60
+ "apps/cad-creator/frontend/src/lib/robotics/runtime/RenderSystem.ts"
61
+ ]
62
+ }
63
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@inneranimalmedia/agentsam-3d-viewer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.6.15",
4
+ "type": "module",
5
+ "description": "Framework-agnostic Three.js viewport and model viewer for AgentSam apps and public sites.",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.d.ts",
9
+ "import": "./src/index.js"
10
+ },
11
+ "./format": {
12
+ "types": "./src/format.d.ts",
13
+ "import": "./src/format.js"
14
+ },
15
+ "./package.json": "./package.json",
16
+ "./occt": {
17
+ "types": "./src/occt.d.ts",
18
+ "import": "./src/occt.js"
19
+ }
20
+ },
21
+ "scripts": {
22
+ "test": "node --test test/*.test.mjs"
23
+ },
24
+ "files": [
25
+ "src/",
26
+ "README.md",
27
+ "agentsam.package.json"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22 <27"
31
+ },
32
+ "license": "FSL-1.1-MIT",
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }
@@ -0,0 +1,3 @@
1
+ export type ModelFormat = 'glb' | 'gltf' | 'stl';
2
+ export function inferModelFormat(source: unknown, explicitFormat?: string): ModelFormat;
3
+ export const SUPPORTED_MODEL_FORMATS: readonly ModelFormat[];
package/src/format.js ADDED
@@ -0,0 +1,24 @@
1
+ const SUPPORTED_FORMATS = new Set(['glb', 'gltf', 'stl']);
2
+
3
+ /** Resolve a model format from an explicit option, URL, or Blob MIME type. */
4
+ export function inferModelFormat(source, explicitFormat) {
5
+ if (explicitFormat != null) {
6
+ const format = String(explicitFormat).toLowerCase().replace(/^\./, '');
7
+ if (!SUPPORTED_FORMATS.has(format)) throw new Error('agentsam_3d_format_unsupported');
8
+ return format;
9
+ }
10
+ if (typeof source === 'string') {
11
+ const pathname = source.split(/[?#]/, 1)[0].toLowerCase();
12
+ const match = pathname.match(/\.(glb|gltf|stl)$/);
13
+ if (match) return match[1];
14
+ }
15
+ if (typeof Blob !== 'undefined' && source instanceof Blob) {
16
+ const mime = String(source.type || '').toLowerCase();
17
+ if (mime === 'model/gltf-binary' || mime === 'model/vnd.gltf.binary') return 'glb';
18
+ if (mime === 'model/gltf+json' || mime === 'model/gltf+json; charset=utf-8') return 'gltf';
19
+ if (mime === 'model/stl' || mime === 'application/sla') return 'stl';
20
+ }
21
+ throw new Error('agentsam_3d_format_required');
22
+ }
23
+
24
+ export const SUPPORTED_MODEL_FORMATS = Object.freeze([...SUPPORTED_FORMATS]);
package/src/index.d.ts ADDED
@@ -0,0 +1,101 @@
1
+ export type ModelFormat = 'glb' | 'gltf' | 'stl';
2
+
3
+ /** The host passes its own Three.js runtime to avoid bundling a second copy. */
4
+ export interface ThreeRuntime {
5
+ THREE: any;
6
+ OrbitControls?: new (camera: any, element: HTMLElement) => any; // required unless controls:false
7
+ GLTFLoader?: new () => any;
8
+ STLLoader?: new () => any;
9
+ }
10
+
11
+ export interface ThreeViewportOptions {
12
+ ariaLabel?: string;
13
+ role?: string;
14
+ background?: string | number;
15
+ wrapper?: boolean;
16
+ insertCanvasFirst?: boolean;
17
+ minHeight?: string;
18
+ cameraUp?: [number, number, number]; // set before OrbitControls initialization
19
+ fov?: number;
20
+ near?: number;
21
+ far?: number;
22
+ maxPixelRatio?: number;
23
+ antialias?: boolean;
24
+ preserveDrawingBuffer?: boolean;
25
+ powerPreference?: WebGLPowerPreference;
26
+ shadowMap?: { enabled?: boolean; type?: any };
27
+ toneMapping?: any;
28
+ toneMappingExposure?: number;
29
+ lights?: boolean;
30
+ showGrid?: boolean;
31
+ gridSize?: number;
32
+ gridDivisions?: number;
33
+ showAxes?: boolean;
34
+ axesSize?: number;
35
+ controls?: boolean; // false for hosts with their own camera controller, e.g. BIM walkthrough
36
+ enableDamping?: boolean;
37
+ dampingFactor?: number;
38
+ minDistance?: number;
39
+ maxDistance?: number;
40
+ autoRender?: boolean;
41
+ onFrame?: (context: { scene: any; camera: any; renderer: ThreeRendererLike; controls: any }) => void;
42
+ }
43
+
44
+ export interface ThreeRendererLike {
45
+ domElement: HTMLCanvasElement;
46
+ setSize(width: number, height: number, updateStyle?: boolean): void;
47
+ setPixelRatio(value: number): void;
48
+ render(scene: any, camera: any): void;
49
+ dispose(): void;
50
+ shadowMap: any;
51
+ capabilities: { getMaxAnisotropy(): number };
52
+ outputColorSpace: any;
53
+ toneMapping: any;
54
+ toneMappingExposure: number;
55
+ }
56
+
57
+ export interface ThreeViewportHandle {
58
+ root: HTMLElement;
59
+ scene: any;
60
+ camera: any;
61
+ renderer: ThreeRendererLike;
62
+ controls: any | null;
63
+ render(): void;
64
+ fit(object: any, padding?: number): { center: any; size: any; distance: number } | null;
65
+ resize(): void;
66
+ start(): void;
67
+ stop(): void;
68
+ dispose(): void;
69
+ }
70
+
71
+ export interface ModelViewerOptions extends ThreeViewportOptions {
72
+ format?: ModelFormat;
73
+ basePath?: string;
74
+ stlColor?: string;
75
+ fitPadding?: number;
76
+ autoRotate?: boolean;
77
+ autoRotateSpeed?: number;
78
+ onLoad?: (model: any) => void;
79
+ onError?: (error: unknown) => void;
80
+ }
81
+
82
+ export interface ModelViewerHandle extends ThreeViewportHandle {
83
+ ready: Promise<any>;
84
+ readonly model: any;
85
+ }
86
+
87
+ export function createThreeViewport(
88
+ container: HTMLElement,
89
+ runtime: ThreeRuntime,
90
+ options?: ThreeViewportOptions,
91
+ ): ThreeViewportHandle;
92
+
93
+ export function mountModelViewer(
94
+ container: HTMLElement,
95
+ source: string | ArrayBuffer | ArrayBufferView | Blob,
96
+ runtime: ThreeRuntime,
97
+ options?: ModelViewerOptions,
98
+ ): ModelViewerHandle;
99
+
100
+ export function inferModelFormat(source: unknown, explicitFormat?: string): ModelFormat;
101
+ export const SUPPORTED_MODEL_FORMATS: readonly ModelFormat[];
package/src/index.js ADDED
@@ -0,0 +1,279 @@
1
+ import { inferModelFormat } from './format.js';
2
+
3
+ export { inferModelFormat, SUPPORTED_MODEL_FORMATS } from './format.js';
4
+
5
+ function validateRuntime(runtime, needsControls = true) {
6
+ if (!runtime?.THREE || typeof runtime.THREE.Scene !== 'function' || (needsControls && typeof runtime.OrbitControls !== 'function')) {
7
+ throw new Error('agentsam_3d_runtime_required');
8
+ }
9
+ return runtime;
10
+ }
11
+
12
+ function asArrayBuffer(value) {
13
+ if (value instanceof ArrayBuffer) return value;
14
+ if (ArrayBuffer.isView(value)) {
15
+ return value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
16
+ }
17
+ throw new Error('agentsam_3d_binary_source_invalid');
18
+ }
19
+
20
+ function disposeObject(object) {
21
+ if (!object) return;
22
+ object.traverse?.((node) => {
23
+ if (!node.isMesh) return;
24
+ node.geometry?.dispose?.();
25
+ const materials = Array.isArray(node.material) ? node.material : [node.material];
26
+ for (const material of materials) {
27
+ if (!material) continue;
28
+ for (const value of Object.values(material)) {
29
+ if (value?.isTexture) value.dispose?.();
30
+ }
31
+ material.dispose?.();
32
+ }
33
+ });
34
+ }
35
+
36
+ /**
37
+ * Create a reusable, framework-agnostic Three.js viewport.
38
+ * Use autoRender:false when the host owns its animation loop or scene interactions.
39
+ */
40
+ export function createThreeViewport(container, runtime, options = {}) {
41
+ const { THREE, OrbitControls } = validateRuntime(runtime, options.controls !== false);
42
+ if (!container || typeof container.appendChild !== 'function') {
43
+ throw new Error('agentsam_3d_container_required');
44
+ }
45
+ const background = options.background ?? '#111722';
46
+ const ownsRoot = options.wrapper !== false;
47
+ const root = ownsRoot ? document.createElement('div') : container;
48
+ if (ownsRoot) {
49
+ root.className = 'agentsam-3d-viewport';
50
+ Object.assign(root.style, {
51
+ position: 'relative',
52
+ width: '100%',
53
+ height: '100%',
54
+ minHeight: options.minHeight ?? '240px',
55
+ overflow: 'hidden',
56
+ background: background === 'transparent' ? 'transparent' : String(background),
57
+ touchAction: 'pan-y',
58
+ });
59
+ root.setAttribute('role', options.role ?? 'img');
60
+ root.setAttribute('aria-label', options.ariaLabel ?? 'Interactive 3D viewport');
61
+ root.tabIndex = 0;
62
+ container.appendChild(root);
63
+ }
64
+
65
+ const scene = new THREE.Scene();
66
+ scene.background = background === 'transparent' ? null : new THREE.Color(background);
67
+ if (options.lights !== false) {
68
+ scene.add(new THREE.HemisphereLight(0xf8fafc, 0x364152, 1.25));
69
+ const key = new THREE.DirectionalLight(0xffffff, 1.65);
70
+ key.position.set(20, 35, 25);
71
+ scene.add(key);
72
+ }
73
+ if (options.showGrid) {
74
+ const grid = new THREE.GridHelper(options.gridSize ?? 10, options.gridDivisions ?? 20, 0x64748b, 0x334155);
75
+ const materials = Array.isArray(grid.material) ? grid.material : [grid.material];
76
+ materials.forEach((material) => { material.transparent = true; material.opacity = 0.28; });
77
+ scene.add(grid);
78
+ }
79
+ if (options.showAxes) scene.add(new THREE.AxesHelper(options.axesSize ?? 1.5));
80
+
81
+ const camera = new THREE.PerspectiveCamera(
82
+ options.fov ?? 42,
83
+ 1,
84
+ options.near ?? 0.01,
85
+ options.far ?? 10000,
86
+ );
87
+ if (options.cameraUp) camera.up.set(...options.cameraUp);
88
+ camera.position.set(4, 3, 5);
89
+ const renderer = new THREE.WebGLRenderer({
90
+ antialias: options.antialias !== false,
91
+ alpha: background === 'transparent',
92
+ preserveDrawingBuffer: options.preserveDrawingBuffer === true,
93
+ powerPreference: options.powerPreference ?? 'high-performance',
94
+ });
95
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, options.maxPixelRatio ?? 2));
96
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
97
+ renderer.shadowMap.enabled = options.shadowMap?.enabled === true;
98
+ if (options.shadowMap?.type !== undefined) renderer.shadowMap.type = options.shadowMap.type;
99
+ renderer.toneMapping = options.toneMapping ?? THREE.NoToneMapping;
100
+ renderer.toneMappingExposure = options.toneMappingExposure ?? 1;
101
+ renderer.setSize(Math.max(1, root.clientWidth || container.clientWidth || 400), Math.max(1, root.clientHeight || container.clientHeight || 300));
102
+ Object.assign(renderer.domElement.style, { display: 'block', width: '100%', height: '100%', outline: 'none' });
103
+ renderer.domElement.setAttribute('aria-hidden', 'true');
104
+ if (options.insertCanvasFirst) root.insertBefore(renderer.domElement, root.firstChild);
105
+ else root.appendChild(renderer.domElement);
106
+
107
+ const controls = options.controls === false ? null : new OrbitControls(camera, renderer.domElement);
108
+ if (controls) {
109
+ controls.enableDamping = options.enableDamping !== false;
110
+ controls.dampingFactor = options.dampingFactor ?? 0.05;
111
+ controls.minDistance = options.minDistance ?? 0.1;
112
+ controls.maxDistance = options.maxDistance ?? 2000;
113
+ controls.update();
114
+ }
115
+
116
+ let disposed = false;
117
+ let frame = 0;
118
+ const resize = () => {
119
+ if (disposed) return;
120
+ const width = Math.max(1, root.clientWidth || container.clientWidth || 1);
121
+ const height = Math.max(1, root.clientHeight || container.clientHeight || 1);
122
+ camera.aspect = width / height;
123
+ camera.updateProjectionMatrix();
124
+ renderer.setSize(width, height, false);
125
+ };
126
+ const resizeObserver = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(resize) : null;
127
+ if (resizeObserver) resizeObserver.observe(root);
128
+ else window.addEventListener('resize', resize);
129
+
130
+ const render = () => {
131
+ if (disposed) return;
132
+ controls?.update();
133
+ renderer.render(scene, camera);
134
+ };
135
+ const tick = () => {
136
+ if (disposed) return;
137
+ frame = requestAnimationFrame(tick);
138
+ if (document.hidden) return;
139
+ options.onFrame?.({ scene, camera, renderer, controls });
140
+ render();
141
+ };
142
+ if (options.autoRender !== false) tick();
143
+
144
+ function fit(object, padding = 1.3) {
145
+ const bounds = new THREE.Box3().setFromObject(object);
146
+ if (bounds.isEmpty()) return null;
147
+ const center = bounds.getCenter(new THREE.Vector3());
148
+ const size = bounds.getSize(new THREE.Vector3());
149
+ const distance = Math.max(size.length() * padding, 1);
150
+ camera.position.copy(center.clone().add(new THREE.Vector3(distance * 0.8, distance * 0.55, distance * 0.8)));
151
+ camera.near = Math.max(distance / 10000, 0.005);
152
+ camera.far = Math.max(distance * 20, 100);
153
+ camera.updateProjectionMatrix();
154
+ if (controls) {
155
+ controls.target.copy(center);
156
+ controls.maxDistance = Math.max(distance * 6, controls.minDistance * 10);
157
+ controls.update();
158
+ } else {
159
+ camera.lookAt(center);
160
+ }
161
+ return { center, size, distance };
162
+ }
163
+
164
+ function stop() {
165
+ if (frame) cancelAnimationFrame(frame);
166
+ frame = 0;
167
+ }
168
+ function start() {
169
+ if (disposed || frame) return;
170
+ tick();
171
+ }
172
+ function dispose() {
173
+ if (disposed) return;
174
+ disposed = true;
175
+ stop();
176
+ resizeObserver?.disconnect();
177
+ if (!resizeObserver) window.removeEventListener('resize', resize);
178
+ controls?.dispose();
179
+ renderer.dispose();
180
+ if (ownsRoot) root.remove();
181
+ else renderer.domElement.remove();
182
+ }
183
+
184
+ return { root, scene, camera, renderer, controls, render, fit, resize, start, stop, dispose };
185
+ }
186
+
187
+ /**
188
+ * Mount an interactive GLB/GLTF/STL viewer into any DOM container.
189
+ * The returned `ready` promise resolves with the loaded Three.js Object3D.
190
+ */
191
+ export function mountModelViewer(container, source, runtime, options = {}) {
192
+ const { THREE, GLTFLoader, STLLoader } = validateRuntime(runtime);
193
+ const format = inferModelFormat(source, options.format);
194
+ if (format === 'stl' && typeof STLLoader !== 'function') throw new Error('agentsam_3d_stl_loader_required');
195
+ if (format !== 'stl' && typeof GLTFLoader !== 'function') throw new Error('agentsam_3d_gltf_loader_required');
196
+ const viewport = createThreeViewport(container, runtime, {
197
+ ...options,
198
+ ariaLabel: options.ariaLabel ?? 'Interactive 3D model viewer',
199
+ autoRender: false,
200
+ });
201
+ const status = document.createElement('div');
202
+ status.setAttribute('role', 'status');
203
+ status.setAttribute('aria-live', 'polite');
204
+ Object.assign(status.style, {
205
+ position: 'absolute',
206
+ inset: '12px auto auto 12px',
207
+ maxWidth: 'calc(100% - 24px)',
208
+ padding: '6px 10px',
209
+ borderRadius: '8px',
210
+ background: 'rgba(15, 23, 42, 0.82)',
211
+ color: '#f8fafc',
212
+ font: '12px/1.4 system-ui, sans-serif',
213
+ });
214
+ status.textContent = 'Loading 3D model…';
215
+ viewport.root.appendChild(status);
216
+
217
+ let model = null;
218
+ let disposed = false;
219
+ const loader = format === 'stl' ? new STLLoader() : new GLTFLoader();
220
+ const ready = (async () => {
221
+ let object;
222
+ if (format === 'stl') {
223
+ const geometry = typeof source === 'string'
224
+ ? await loader.loadAsync(source)
225
+ : loader.parse(await (source instanceof Blob ? source.arrayBuffer() : Promise.resolve(asArrayBuffer(source))));
226
+ geometry.computeVertexNormals();
227
+ object = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({
228
+ color: options.stlColor ?? '#c8d4e4', roughness: 0.72, metalness: 0.06,
229
+ }));
230
+ } else {
231
+ const gltf = typeof source === 'string'
232
+ ? await loader.loadAsync(source)
233
+ : await loader.parseAsync(
234
+ await (source instanceof Blob ? source.arrayBuffer() : Promise.resolve(asArrayBuffer(source))),
235
+ options.basePath ?? '',
236
+ );
237
+ object = gltf.scene;
238
+ }
239
+ if (disposed) { disposeObject(object); return object; }
240
+ model = object;
241
+ model.traverse?.((node) => {
242
+ if (!node.isMesh) return;
243
+ node.castShadow = true;
244
+ node.receiveShadow = true;
245
+ });
246
+ viewport.scene.add(model);
247
+ viewport.fit(model, options.fitPadding ?? 1.3);
248
+ status.remove();
249
+ options.onLoad?.(model);
250
+ return model;
251
+ })().catch((error) => {
252
+ if (!disposed) status.textContent = '3D model could not be loaded.';
253
+ options.onError?.(error);
254
+ throw error;
255
+ });
256
+
257
+ let frame = 0;
258
+ const tick = () => {
259
+ if (disposed) return;
260
+ frame = requestAnimationFrame(tick);
261
+ if (document.hidden) return;
262
+ if (options.autoRotate && model) model.rotation.y += options.autoRotateSpeed ?? 0.003;
263
+ viewport.render();
264
+ };
265
+ tick();
266
+
267
+ return {
268
+ ...viewport,
269
+ ready,
270
+ get model() { return model; },
271
+ dispose() {
272
+ if (disposed) return;
273
+ disposed = true;
274
+ if (frame) cancelAnimationFrame(frame);
275
+ disposeObject(model);
276
+ viewport.dispose();
277
+ },
278
+ };
279
+ }
package/src/occt.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export interface OcctDisplayMesh {
2
+ units: 'mm';
3
+ axes: 'z-up';
4
+ positions: ArrayLike<number>;
5
+ normals: ArrayLike<number>;
6
+ indices: ArrayLike<number>;
7
+ }
8
+ export function createOcctMeshGeometry(
9
+ mesh: OcctDisplayMesh,
10
+ runtime: { THREE: any } | any,
11
+ options?: { planYSign?: 1 | -1 },
12
+ ): any;
package/src/occt.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Display adapter for a verified native OCCT mesh. Native B-rep remains the
3
+ * geometry authority; this function only converts its tessellation for Three.js.
4
+ * Contract: millimeters, Z-up, positions and normals per vertex, triangle indices.
5
+ */
6
+ export function createOcctMeshGeometry(mesh, runtime, options = {}) {
7
+ const THREE = runtime?.THREE ?? runtime;
8
+ if (typeof THREE?.BufferGeometry !== 'function' || typeof THREE?.BufferAttribute !== 'function') {
9
+ throw new Error('agentsam_occt_three_runtime_required');
10
+ }
11
+ if (mesh?.units !== 'mm' || mesh?.axes !== 'z-up') throw new Error('native_mesh_coordinate_contract_invalid');
12
+ const positions = mesh.positions, normals = mesh.normals, indices = mesh.indices;
13
+ if (!Array.isArray(positions) && !ArrayBuffer.isView(positions)) throw new Error('native_mesh_positions_invalid');
14
+ if (!Array.isArray(normals) && !ArrayBuffer.isView(normals)) throw new Error('native_mesh_normals_invalid');
15
+ if (!Array.isArray(indices) && !ArrayBuffer.isView(indices)) throw new Error('native_mesh_indices_invalid');
16
+ if (positions.length === 0 || positions.length % 3 || normals.length !== positions.length || indices.length % 3) {
17
+ throw new Error('native_mesh_topology_invalid');
18
+ }
19
+ const vertexCount = positions.length / 3;
20
+ // Validate without duplicating potentially millions of vertex scalars.
21
+ for (let i = 0; i < positions.length; i++) {
22
+ if (!Number.isFinite(positions[i]) || !Number.isFinite(normals[i])) {
23
+ throw new Error('native_mesh_values_invalid');
24
+ }
25
+ }
26
+ for (let i = 0; i < indices.length; i++) {
27
+ const index = indices[i];
28
+ if (!Number.isSafeInteger(index) || index < 0 || index >= vertexCount) {
29
+ throw new Error('native_mesh_values_invalid');
30
+ }
31
+ }
32
+ const sign = options.planYSign ?? -1;
33
+ if (sign !== -1 && sign !== 1) throw new Error('native_mesh_axis_sign_invalid');
34
+ const points = new Float32Array(positions.length);
35
+ const shading = new Float32Array(normals.length);
36
+ for (let i = 0; i < points.length; i += 3) {
37
+ points[i] = positions[i] * .001;
38
+ points[i+1] = positions[i+2] * .001;
39
+ points[i+2] = positions[i+1] === 0 ? 0 : positions[i+1] * .001 * sign;
40
+ shading[i] = normals[i];
41
+ shading[i+1] = normals[i+2];
42
+ shading[i+2] = normals[i+1] === 0 ? 0 : normals[i+1] * sign;
43
+ }
44
+ const triangles = Array.from(indices);
45
+ if (sign === 1) {
46
+ for (let i = 0; i < triangles.length; i += 3) [triangles[i+1], triangles[i+2]] = [triangles[i+2], triangles[i+1]];
47
+ }
48
+ const geometry = new THREE.BufferGeometry();
49
+ geometry.setAttribute('position', new THREE.BufferAttribute(points, 3));
50
+ geometry.setAttribute('normal', new THREE.BufferAttribute(shading, 3));
51
+ geometry.setIndex(triangles);
52
+ geometry.computeBoundingSphere();
53
+ return geometry;
54
+ }