@selvajs/compute 1.5.3 → 2.0.0-beta.1
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/dist/chunk-3FH7FKLG.cjs +2 -0
- package/dist/chunk-3FH7FKLG.cjs.map +1 -0
- package/dist/chunk-DELOBV2Q.js +2 -0
- package/dist/chunk-DELOBV2Q.js.map +1 -0
- package/dist/chunk-GTTKNF4G.js +4 -0
- package/dist/chunk-GTTKNF4G.js.map +1 -0
- package/dist/chunk-JFLD2UCY.cjs +2 -0
- package/dist/chunk-JFLD2UCY.cjs.map +1 -0
- package/dist/chunk-MA6YB3YZ.cjs +4 -0
- package/dist/chunk-MA6YB3YZ.cjs.map +1 -0
- package/dist/chunk-MKW2KTPT.js +2 -0
- package/dist/chunk-MKW2KTPT.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +10 -15
- package/dist/core.d.ts +10 -15
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +77 -101
- package/dist/grasshopper.d.ts +77 -101
- package/dist/grasshopper.js +1 -1
- package/dist/handle-files-DsrxHKHP.d.cts +262 -0
- package/dist/handle-files-DsrxHKHP.d.ts +262 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/{types-Dfeei0dD.d.cts → types-CJ092lxB.d.cts} +116 -73
- package/dist/types-D1SkNje_.d.cts +87 -0
- package/dist/types-D1SkNje_.d.ts +87 -0
- package/dist/{types-Dfeei0dD.d.ts → types-XCUrJGby.d.ts} +116 -73
- package/dist/visualization-GU7JIB4V.cjs +2 -0
- package/dist/visualization-GU7JIB4V.cjs.map +1 -0
- package/dist/visualization-WIUVT2FZ.js +2 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.cjs.map +1 -1
- package/dist/visualization.d.cts +16 -21
- package/dist/visualization.d.ts +16 -21
- package/dist/visualization.js +1 -1
- package/package.json +18 -7
- package/dist/chunk-GZYSQSLH.cjs +0 -2
- package/dist/chunk-GZYSQSLH.cjs.map +0 -1
- package/dist/chunk-JZYEMZZ5.js +0 -2
- package/dist/chunk-JZYEMZZ5.js.map +0 -1
- package/dist/chunk-OEDLGVIQ.js +0 -2
- package/dist/chunk-OEDLGVIQ.js.map +0 -1
- package/dist/chunk-OW6HV6QP.js +0 -2
- package/dist/chunk-OW6HV6QP.js.map +0 -1
- package/dist/chunk-RBNF6MNH.cjs +0 -3
- package/dist/chunk-RBNF6MNH.cjs.map +0 -1
- package/dist/chunk-SVEXPGHW.cjs +0 -2
- package/dist/chunk-SVEXPGHW.cjs.map +0 -1
- package/dist/chunk-XBIEAJBK.js +0 -3
- package/dist/chunk-XBIEAJBK.js.map +0 -1
- package/dist/chunk-ZRQRYG6F.cjs +0 -2
- package/dist/chunk-ZRQRYG6F.cjs.map +0 -1
- package/dist/errors-CEy4nM1J.d.cts +0 -149
- package/dist/errors-CEy4nM1J.d.ts +0 -149
- package/dist/types-COCuQEMk.d.cts +0 -93
- package/dist/types-COCuQEMk.d.ts +0 -93
- package/dist/visualization-ENMBHWIN.js +0 -2
- package/dist/visualization-TBPFFBFU.cjs +0 -2
- package/dist/visualization-TBPFFBFU.cjs.map +0 -1
- /package/dist/{visualization-ENMBHWIN.js.map → visualization-WIUVT2FZ.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/features/visualization/threejs/three-initializer.ts","../src/features/visualization/threejs/three-helpers.ts","../src/features/visualization/threejs/three-materials.ts","../src/features/visualization/webdisplay/binary-parser.ts","../src/features/visualization/webdisplay/batch-parser.ts","../src/features/visualization/webdisplay/webdisplay-parser.ts"],"sourcesContent":["import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { HDRLoader } from 'three/addons/loaders/HDRLoader.js';\n\nimport { getLogger } from '@/core';\nimport { ThreeInitializerOptions } from '../types';\n\nconst defaultUp = new THREE.Vector3(0, 0, 1);\n\n// Returns scale-specific values for mm, cm, and m scales\nconst getScaleValue = (scale: string, mmVal: number, cmVal: number, mVal: number): number => {\n\tswitch (scale) {\n\t\tcase 'mm':\n\t\t\treturn mmVal;\n\t\tcase 'cm':\n\t\t\treturn cmVal;\n\t\tdefault:\n\t\t\treturn mVal;\n\t}\n};\n\n/**\n * Initializes a Three.js environment with scene, camera, renderer, and event handling.\n */\nexport const initThree = function (\n\tcanvas: HTMLCanvasElement,\n\toptions?: ThreeInitializerOptions\n): {\n\tscene: THREE.Scene;\n\tcamera: THREE.PerspectiveCamera;\n\tcontrols: OrbitControls;\n\trenderer: THREE.WebGLRenderer;\n\tdispose: () => void;\n\tfitToView: () => void;\n\tclearSelection: () => void;\n} {\n\tconst config = applyDefaults(options || {});\n\n\tconst scene = createScene(config);\n\tconst camera = createCamera(config, canvas);\n\tconst renderer = setupRenderer(canvas, config);\n\tconst controls = setupControls(camera, canvas, config);\n\n\tsetupEnvironment(scene, config);\n\tsetupLighting(scene, config);\n\n\tif (config.floor?.enabled) {\n\t\taddFloor(scene, config);\n\t}\n\n\tconst eventHandlers =\n\t\tconfig.events.enableEventHandlers !== false\n\t\t\t? setupEventHandlers(canvas, scene, camera, controls, config)\n\t\t\t: { dispose: () => {}, fitToView: () => {}, clearSelection: () => {} };\n\n\tconst parent = canvas.parentElement;\n\tconst getCanvasSize = () =>\n\t\tparent\n\t\t\t? { width: parent.clientWidth, height: parent.clientHeight }\n\t\t\t: { width: window.innerWidth, height: window.innerHeight };\n\n\t// Resize checked every frame so buffer resize and render happen in the same frame,\n\t// preventing visible blank frames on resize\n\tconst { animate, dispose: disposeAnimation } = createAnimationLoop(\n\t\trenderer,\n\t\tscene,\n\t\tcamera,\n\t\tcontrols,\n\t\tgetCanvasSize,\n\t\tconfig.events.onFrame\n\t);\n\tanimate();\n\n\tconst sceneUp = config.environment?.sceneUp || defaultUp;\n\tscene.up.set(sceneUp.x, sceneUp.y, sceneUp.z);\n\n\tconst dispose = () => {\n\t\tdisposeAnimation();\n\t\teventHandlers.dispose();\n\t\tcontrols.dispose();\n\t\trenderer.dispose();\n\n\t\tscene.traverse((object) => {\n\t\t\tif (object instanceof THREE.Mesh) {\n\t\t\t\tobject.geometry?.dispose();\n\t\t\t\tif (Array.isArray(object.material)) {\n\t\t\t\t\tobject.material.forEach((material) => material.dispose());\n\t\t\t\t} else {\n\t\t\t\t\tobject.material?.dispose();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t};\n\n\treturn {\n\t\tscene,\n\t\tcamera,\n\t\tcontrols,\n\t\trenderer,\n\t\tdispose,\n\t\tfitToView: eventHandlers.fitToView,\n\t\tclearSelection: eventHandlers.clearSelection\n\t};\n};\n\nfunction applyDefaults(options: ThreeInitializerOptions): Required<ThreeInitializerOptions> {\n\tconst scale = options.sceneScale || 'm';\n\n\t// All Rhino geometry is normalized to METERS (1 unit = 1 meter), sceneScale just changes the viewing perspective\n\tconst scaleDefaults = {\n\t\tmm: {\n\t\t\tcameraDistance: 20,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 100,\n\t\t\tlightDistance: 10,\n\t\t\tlightHeight: 20,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 1000\n\t\t},\n\t\tcm: {\n\t\t\tcameraDistance: 20,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 100,\n\t\t\tlightDistance: 25,\n\t\t\tlightHeight: 50,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 100\n\t\t},\n\t\tm: {\n\t\t\tcameraDistance: 10,\n\t\t\tnear: 0.01,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 50,\n\t\t\tlightDistance: 25,\n\t\t\tlightHeight: 50,\n\t\t\tminDistance: 0.001,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 1\n\t\t},\n\t\tinches: {\n\t\t\tcameraDistance: 15,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 80,\n\t\t\tlightDistance: 20,\n\t\t\tlightHeight: 40,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 80,\n\t\t\tscaleFactor: 39.37\n\t\t},\n\t\tfeet: {\n\t\t\tcameraDistance: 8,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 40,\n\t\t\tlightDistance: 15,\n\t\t\tlightHeight: 30,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 60,\n\t\t\tscaleFactor: 3.28084\n\t\t}\n\t};\n\n\tconst defaults = scaleDefaults[scale];\n\n\treturn {\n\t\tsceneScale: scale,\n\t\tcamera: {\n\t\t\tposition:\n\t\t\t\toptions.camera?.position ||\n\t\t\t\tnew THREE.Vector3(\n\t\t\t\t\t-defaults.cameraDistance,\n\t\t\t\t\tdefaults.cameraDistance,\n\t\t\t\t\tdefaults.cameraDistance\n\t\t\t\t),\n\t\t\tfov: options.camera?.fov || 20,\n\t\t\tnear: options.camera?.near || defaults.near,\n\t\t\tfar: options.camera?.far || defaults.far,\n\t\t\ttarget: options.camera?.target || new THREE.Vector3(0, 0, 0)\n\t\t},\n\t\tlighting: {\n\t\t\tenableSunlight: options.lighting?.enableSunlight ?? true,\n\t\t\tsunlightIntensity: options.lighting?.sunlightIntensity || 1,\n\t\t\tsunlightPosition:\n\t\t\t\toptions.lighting?.sunlightPosition ||\n\t\t\t\tnew THREE.Vector3(defaults.lightDistance, defaults.lightHeight, defaults.lightDistance),\n\t\t\tambientLightColor: options.lighting?.ambientLightColor || new THREE.Color(0x404040),\n\t\t\tambientLightIntensity: options.lighting?.ambientLightIntensity || 1,\n\t\t\tsunlightColor: options.lighting?.sunlightColor || 0xffffff // Default to white sunlight\n\t\t},\n\t\tenvironment: {\n\t\t\thdrPath: options.environment?.hdrPath || '/baseHDR.hdr',\n\t\t\tbackgroundColor: options.environment?.backgroundColor || new THREE.Color(0xf0f0f0),\n\t\t\tenableEnvironmentLighting: options.environment?.enableEnvironmentLighting ?? true,\n\t\t\tsceneUp: options.environment?.sceneUp || defaultUp,\n\t\t\tshowEnvironment: options.environment?.showEnvironment ?? false\n\t\t},\n\t\tfloor: {\n\t\t\tenabled: options.floor?.enabled ?? false,\n\t\t\tsize: options.floor?.size || defaults.floorSize,\n\t\t\tcolor: options.floor?.color || new THREE.Color(0x808080),\n\t\t\troughness: options.floor?.roughness || 0.7,\n\t\t\tmetalness: options.floor?.metalness || 0.0,\n\t\t\treceiveShadow: options.floor?.receiveShadow ?? true\n\t\t},\n\t\trender: {\n\t\t\tenableShadows: options.render?.enableShadows ?? true,\n\t\t\tshadowMapSize: options.render?.shadowMapSize || 2048,\n\t\t\tantialias: options.render?.antialias ?? true,\n\t\t\tpixelRatio: options.render?.pixelRatio || Math.min(window.devicePixelRatio, 2),\n\t\t\ttoneMapping: options.render?.toneMapping || THREE.NeutralToneMapping,\n\t\t\ttoneMappingExposure: options.render?.toneMappingExposure || 1,\n\t\t\tpreserveDrawingBuffer: options.render?.preserveDrawingBuffer ?? false\n\t\t},\n\t\tcontrols: {\n\t\t\tenableDamping: options.controls?.enableDamping ?? false,\n\t\t\tdampingFactor: options.controls?.dampingFactor || 0.05,\n\t\t\tautoRotate: options.controls?.autoRotate ?? false,\n\t\t\tautoRotateSpeed: options.controls?.autoRotateSpeed || 0.5,\n\t\t\tenableZoom: options.controls?.enableZoom ?? true,\n\t\t\tenablePan: options.controls?.enablePan ?? true,\n\t\t\tminDistance: options.controls?.minDistance || defaults.minDistance,\n\t\t\tmaxDistance: options.controls?.maxDistance || Infinity\n\t\t},\n\t\tevents: {\n\t\t\tonBackgroundClicked: options.events?.onBackgroundClicked,\n\t\t\tonObjectSelected: options.events?.onObjectSelected,\n\t\t\tonMeshMetadataClicked: options.events?.onMeshMetadataClicked,\n\t\t\tonMeshDoubleClicked: options.events?.onMeshDoubleClicked,\n\t\t\tselectionColor: options.events?.selectionColor || '#ff0000', // Default to red\n\t\t\tenableEventHandlers: options.events?.enableEventHandlers ?? true,\n\t\t\tenableKeyboardControls: options.events?.enableKeyboardControls ?? true,\n\t\t\tenableClickToFocus: options.events?.enableClickToFocus ?? true,\n\t\t\tenableDoubleClickZoom: options.events?.enableDoubleClickZoom ?? true,\n\t\t\tonReady: options.events?.onReady,\n\t\t\tonFrame: options.events?.onFrame\n\t\t}\n\t};\n}\n\nfunction createScene(config: Required<ThreeInitializerOptions>): THREE.Scene {\n\tconst scene = new THREE.Scene();\n\n\tconst bgColor =\n\t\ttypeof config.environment.backgroundColor === 'string'\n\t\t\t? new THREE.Color(config.environment.backgroundColor)\n\t\t\t: config.environment.backgroundColor;\n\tscene.background = bgColor || null;\n\n\treturn scene;\n}\n\nfunction animateCameraTo(\n\tcamera: THREE.PerspectiveCamera,\n\tcontrols: OrbitControls,\n\ttoPosition: THREE.Vector3,\n\ttoTarget: THREE.Vector3,\n\tdurationMs = 200\n): void {\n\tconst fromPosition = camera.position.clone();\n\tconst fromTarget = controls.target.clone();\n\tconst startTime = performance.now();\n\n\tconst easeOut = (t: number) => 1 - Math.pow(1 - t, 3);\n\n\tconst tick = () => {\n\t\tconst elapsed = performance.now() - startTime;\n\t\tconst t = easeOut(Math.min(elapsed / durationMs, 1));\n\n\t\tcamera.position.lerpVectors(fromPosition, toPosition, t);\n\t\tcontrols.target.lerpVectors(fromTarget, toTarget, t);\n\t\tcontrols.update();\n\n\t\tif (t < 1) requestAnimationFrame(tick);\n\t};\n\n\trequestAnimationFrame(tick);\n}\n\n// Resize applied before render so buffer clear and draw happen in the same frame,\n// preventing visible blank frames when the canvas is resized\nfunction createAnimationLoop(\n\trenderer: THREE.WebGLRenderer,\n\tscene: THREE.Scene,\n\tcamera: THREE.PerspectiveCamera,\n\tcontrols: OrbitControls,\n\tgetCanvasSize: () => { width: number; height: number },\n\tonFrame?: (delta: number) => void\n): { animate: () => void; dispose: () => void } {\n\tlet animationId: number | null = null;\n\tlet lastTime = performance.now();\n\n\tconst checkResize = () => {\n\t\tconst { width, height } = getCanvasSize();\n\t\tif (width === 0 || height === 0) return;\n\n\t\tconst pixelRatio = Math.min(window.devicePixelRatio, 2);\n\t\tconst newW = Math.round(width * pixelRatio);\n\t\tconst newH = Math.round(height * pixelRatio);\n\n\t\tif (renderer.domElement.width !== newW || renderer.domElement.height !== newH) {\n\t\t\trenderer.setPixelRatio(pixelRatio);\n\t\t\trenderer.setSize(width, height, false);\n\t\t\tcamera.aspect = width / height;\n\t\t\tcamera.updateProjectionMatrix();\n\t\t}\n\t};\n\n\tconst animate = function () {\n\t\tanimationId = requestAnimationFrame(animate);\n\n\t\tconst now = performance.now();\n\t\tconst delta = (now - lastTime) / 1000;\n\t\tlastTime = now;\n\n\t\tcheckResize();\n\n\t\tif (controls.enableDamping || controls.autoRotate) {\n\t\t\tcontrols.update();\n\t\t}\n\n\t\tonFrame?.(delta);\n\n\t\trenderer.render(scene, camera);\n\t};\n\n\tconst dispose = () => {\n\t\tif (animationId !== null) {\n\t\t\tcancelAnimationFrame(animationId);\n\t\t\tanimationId = null;\n\t\t}\n\t};\n\n\treturn { animate, dispose };\n}\n\nfunction setupEnvironment(scene: THREE.Scene, config: Required<ThreeInitializerOptions>) {\n\tif (config.environment.enableEnvironmentLighting) {\n\t\tnew HDRLoader().load(\n\t\t\tconfig.environment.hdrPath || '/baseHDR.hdr',\n\t\t\tfunction (envMap) {\n\t\t\t\tenvMap.mapping = THREE.EquirectangularReflectionMapping;\n\t\t\t\tscene.environment = envMap;\n\t\t\t\tif (config.environment.showEnvironment) {\n\t\t\t\t\tscene.background = envMap;\n\t\t\t\t}\n\t\t\t\tconfig.events.onReady?.();\n\t\t\t},\n\t\t\tundefined,\n\t\t\tfunction (error) {\n\t\t\t\tgetLogger().warn('HDR texture could not be loaded, falling back to basic lighting:', error);\n\t\t\t\tconfig.events.onReady?.();\n\t\t\t}\n\t\t);\n\t} else {\n\t\tconfig.events.onReady?.();\n\t}\n}\n\nfunction setupLighting(scene: THREE.Scene, config: Required<ThreeInitializerOptions>) {\n\tconst ambientLight = new THREE.AmbientLight(\n\t\tconfig.lighting.ambientLightColor,\n\t\tconfig.lighting.ambientLightIntensity\n\t);\n\tscene.add(ambientLight);\n\n\tif (config.lighting.enableSunlight) {\n\t\tconst sunlight = new THREE.DirectionalLight(\n\t\t\tconfig.lighting.sunlightColor ?? 0xffffff,\n\t\t\tconfig.lighting.sunlightIntensity\n\t\t);\n\t\tconst pos = config.lighting.sunlightPosition;\n\t\tif (pos) {\n\t\t\tsunlight.position.set(pos.x, pos.y, pos.z);\n\t\t}\n\n\t\tif (config.render.enableShadows) {\n\t\t\tsunlight.castShadow = true;\n\t\t\tconst shadowSize = getScaleValue(config.sceneScale, 0.1, 10, 100);\n\n\t\t\tsunlight.shadow.camera.left = -shadowSize;\n\t\t\tsunlight.shadow.camera.right = shadowSize;\n\t\t\tsunlight.shadow.camera.top = shadowSize;\n\t\t\tsunlight.shadow.camera.bottom = -shadowSize;\n\n\t\t\tconst shadowNear = getScaleValue(config.sceneScale, 0.001, 0.1, 0.5);\n\t\t\tconst shadowFar = getScaleValue(config.sceneScale, 1, 100, 500);\n\n\t\t\tsunlight.shadow.camera.near = shadowNear;\n\t\t\tsunlight.shadow.camera.far = shadowFar;\n\n\t\t\tsunlight.shadow.mapSize.width = config.render.shadowMapSize || 2048;\n\t\t\tsunlight.shadow.mapSize.height = config.render.shadowMapSize || 2048;\n\n\t\t\tsunlight.shadow.bias = -0.0001;\n\t\t\tsunlight.shadow.normalBias = 0.02;\n\t\t}\n\n\t\tscene.add(sunlight);\n\t}\n}\n\nfunction addFloor(scene: THREE.Scene, config: Required<ThreeInitializerOptions>) {\n\tconst floorSize = config.floor.size;\n\tconst floorGeometry = new THREE.PlaneGeometry(floorSize, floorSize);\n\n\tconst floorColor =\n\t\ttypeof config.floor.color === 'string'\n\t\t\t? new THREE.Color(config.floor.color)\n\t\t\t: config.floor.color;\n\n\tconst floorMaterial = new THREE.MeshStandardMaterial({\n\t\tcolor: floorColor,\n\t\troughness: config.floor.roughness,\n\t\tmetalness: config.floor.metalness,\n\t\tside: THREE.DoubleSide\n\t});\n\n\tconst floor = new THREE.Mesh(floorGeometry, floorMaterial);\n\tfloor.userData.id = 'floor';\n\tfloor.name = 'floor';\n\tfloor.rotation.x = -Math.PI / 2;\n\tfloor.position.y = 0;\n\n\tif (config.floor.receiveShadow && config.render.enableShadows) {\n\t\tfloor.receiveShadow = true;\n\t}\n\n\tscene.add(floor);\n}\n\nfunction createCamera(\n\tconfig: Required<ThreeInitializerOptions>,\n\tcanvas: HTMLCanvasElement\n): THREE.PerspectiveCamera {\n\tconst parent = canvas.parentElement;\n\tconst width = parent ? parent.clientWidth : window.innerWidth;\n\tconst height = parent ? parent.clientHeight : window.innerHeight;\n\n\tconst camera = new THREE.PerspectiveCamera(\n\t\tconfig.camera.fov,\n\t\twidth / height,\n\t\tconfig.camera.near,\n\t\tconfig.camera.far\n\t);\n\n\tconst pos = config.camera.position;\n\tif (pos) {\n\t\tcamera.position.set(pos.x, pos.y, pos.z);\n\t}\n\n\treturn camera;\n}\n\n// Logarithmic depth buffer improves depth precision for mixed scales (mm to km)\nfunction setupRenderer(\n\tcanvas: HTMLCanvasElement,\n\tconfig: Required<ThreeInitializerOptions>\n): THREE.WebGLRenderer {\n\tconst renderer = new THREE.WebGLRenderer({\n\t\tantialias: config.render.antialias,\n\t\tcanvas,\n\t\talpha: true,\n\t\tpowerPreference: 'high-performance',\n\t\tpreserveDrawingBuffer: config.render.preserveDrawingBuffer,\n\t\tlogarithmicDepthBuffer: true\n\t});\n\n\tconst parent = canvas.parentElement;\n\tconst width = parent ? parent.clientWidth : window.innerWidth;\n\tconst height = parent ? parent.clientHeight : window.innerHeight;\n\n\tif (parent) {\n\t\tcanvas.style.width = '100%';\n\t\tcanvas.style.height = '100%';\n\t\tcanvas.style.display = 'block';\n\t}\n\n\trenderer.setSize(width, height, false);\n\trenderer.setPixelRatio(config.render.pixelRatio || Math.min(window.devicePixelRatio, 2));\n\n\tif (config.render.enableShadows) {\n\t\trenderer.shadowMap.enabled = true;\n\t\trenderer.shadowMap.type = THREE.VSMShadowMap;\n\t}\n\n\trenderer.toneMapping = config.render.toneMapping!;\n\trenderer.toneMappingExposure = config.render.toneMappingExposure || 1.0;\n\trenderer.outputColorSpace = THREE.SRGBColorSpace;\n\n\trenderer.sortObjects = true;\n\n\treturn renderer;\n}\n\nfunction setupEventHandlers(\n\tcanvas: HTMLCanvasElement,\n\tscene: THREE.Scene,\n\tcamera: THREE.PerspectiveCamera,\n\tcontrols: OrbitControls,\n\tconfig: Required<ThreeInitializerOptions>\n): {\n\tdispose: () => void;\n\tfitToView: () => void;\n\tclearSelection: () => void;\n} {\n\tconst selectedObjects = new Set<THREE.Object3D>();\n\tconst originalMaterials = new Map<THREE.Object3D, THREE.Material | THREE.Material[]>();\n\tconst raycaster = new THREE.Raycaster();\n\tconst mouse = new THREE.Vector2();\n\tconst mouseDownPosition = new THREE.Vector2();\n\n\t// An object is hittable only if every ancestor is also visible. Three.js's\n\t// recursive intersect doesn't enforce that — it can hit a visible Mesh inside\n\t// a hidden Group.\n\tconst isFullyVisible = (object: THREE.Object3D): boolean => {\n\t\tlet current: THREE.Object3D | null = object;\n\t\twhile (current) {\n\t\t\tif (!current.visible) return false;\n\t\t\tcurrent = current.parent;\n\t\t}\n\t\treturn true;\n\t};\n\n\tconst fitToView = () => {\n\t\tconst box = new THREE.Box3();\n\n\t\tscene.traverse((object) => {\n\t\t\tif (object.visible && object.userData.id !== 'floor' && object instanceof THREE.Mesh) {\n\t\t\t\tbox.expandByObject(object);\n\t\t\t}\n\t\t});\n\n\t\tif (box.isEmpty()) {\n\t\t\tgetLogger().warn('No objects to fit to view');\n\t\t\treturn;\n\t\t}\n\n\t\tconst center = box.getCenter(new THREE.Vector3());\n\t\tconst size = box.getSize(new THREE.Vector3());\n\n\t\tconst maxDim = Math.max(size.x, size.y, size.z);\n\t\tconst fov = camera.fov * (Math.PI / 180);\n\t\tlet distance = maxDim / (2 * Math.tan(fov / 2));\n\n\t\tdistance *= 1.5;\n\n\t\tconst direction = camera.position.clone().sub(controls.target).normalize();\n\t\tcamera.position.copy(center.clone().add(direction.multiplyScalar(distance)));\n\n\t\tcontrols.target.copy(center);\n\t\tcontrols.update();\n\t};\n\n\tconst selectionColorObj =\n\t\ttypeof config.events.selectionColor === 'string'\n\t\t\t? new THREE.Color(config.events.selectionColor)\n\t\t\t: config.events.selectionColor instanceof THREE.Color\n\t\t\t\t? config.events.selectionColor\n\t\t\t\t: new THREE.Color('#ff0000');\n\n\tconst clearSelection = () => {\n\t\tselectedObjects.forEach((obj) => {\n\t\t\tif (obj instanceof THREE.Mesh && originalMaterials.has(obj)) {\n\t\t\t\tobj.material = originalMaterials.get(obj)!;\n\t\t\t\toriginalMaterials.delete(obj);\n\t\t\t}\n\t\t});\n\t\tselectedObjects.clear();\n\t};\n\n\tconst handleMouseDown = (event: MouseEvent) => {\n\t\tmouseDownPosition.set(event.clientX, event.clientY);\n\t};\n\n\tconst handleCanvasClick = (event: MouseEvent) => {\n\t\t// Ignore if mouse has moved (drag)\n\t\tconst currentMousePosition = new THREE.Vector2(event.clientX, event.clientY);\n\t\tif (mouseDownPosition.distanceTo(currentMousePosition) > 5) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tmouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tmouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\traycaster.setFromCamera(mouse, camera);\n\t\tconst intersects = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => isFullyVisible(i.object));\n\n\t\tif (intersects.length > 0) {\n\t\t\tconst clickedObject = intersects[0].object;\n\n\t\t\tif (!selectedObjects.has(clickedObject)) {\n\t\t\t\tclearSelection();\n\t\t\t\tselectedObjects.add(clickedObject);\n\n\t\t\t\t// Clone material so we don't affect other meshes\n\t\t\t\tif (\n\t\t\t\t\tclickedObject instanceof THREE.Mesh &&\n\t\t\t\t\tclickedObject.material instanceof THREE.Material\n\t\t\t\t) {\n\t\t\t\t\toriginalMaterials.set(clickedObject, clickedObject.material);\n\n\t\t\t\t\tconst clonedMaterial = clickedObject.material.clone();\n\t\t\t\t\t(clonedMaterial as any).emissive = selectionColorObj.clone();\n\t\t\t\t\tclickedObject.material = clonedMaterial;\n\t\t\t\t}\n\n\t\t\t\tconfig.events?.onObjectSelected?.(clickedObject);\n\n\t\t\t\tif (clickedObject instanceof THREE.Mesh && Object.keys(clickedObject.userData).length > 0) {\n\t\t\t\t\tconfig.events?.onMeshMetadataClicked?.(clickedObject.userData);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tclearSelection();\n\t\t\tconfig.events?.onBackgroundClicked?.({ x: mouse.x, y: mouse.y });\n\t\t}\n\t};\n\n\tconst handleDoubleClick = (event: MouseEvent) => {\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tmouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tmouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\traycaster.setFromCamera(mouse, camera);\n\t\tconst intersects = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => isFullyVisible(i.object));\n\n\t\tif (intersects.length === 0) return;\n\n\t\tconst target = intersects[0].object;\n\t\tconfig.events?.onMeshDoubleClicked?.(target);\n\n\t\tif (!config.events?.enableDoubleClickZoom) return;\n\n\t\tconst box = new THREE.Box3().setFromObject(target);\n\t\tif (box.isEmpty()) return;\n\n\t\tconst center = box.getCenter(new THREE.Vector3());\n\t\tconst size = box.getSize(new THREE.Vector3());\n\t\tconst maxDim = Math.max(size.x, size.y, size.z);\n\t\tconst fov = camera.fov * (Math.PI / 180);\n\t\tconst distance = (maxDim / (2 * Math.tan(fov / 2))) * 1.5;\n\n\t\tconst direction = camera.position.clone().sub(controls.target).normalize();\n\t\tconst targetPosition = center.clone().add(direction.multiplyScalar(distance));\n\n\t\tanimateCameraTo(camera, controls, targetPosition, center);\n\t};\n\n\tconst handleKeydown = (event: KeyboardEvent) => {\n\t\tif (!config.events?.enableKeyboardControls) return;\n\n\t\tswitch (event.key.toLowerCase()) {\n\t\t\tcase 'f':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfitToView();\n\t\t\t\tbreak;\n\t\t\tcase 'escape':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tclearSelection();\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfitToView();\n\t\t\t\tbreak;\n\t\t}\n\t};\n\n\tif (config.events?.enableClickToFocus) {\n\t\tcanvas.addEventListener('mousedown', handleMouseDown);\n\t\tcanvas.addEventListener('click', handleCanvasClick);\n\t\tcanvas.addEventListener('dblclick', handleDoubleClick);\n\t}\n\n\tif (config.events?.enableKeyboardControls) {\n\t\tcanvas.setAttribute('tabindex', '0');\n\t\tcanvas.addEventListener('keydown', handleKeydown);\n\t}\n\n\tconst dispose = () => {\n\t\tcanvas.removeEventListener('mousedown', handleMouseDown);\n\t\tcanvas.removeEventListener('click', handleCanvasClick);\n\t\tcanvas.removeEventListener('dblclick', handleDoubleClick);\n\t\tcanvas.removeEventListener('keydown', handleKeydown);\n\t\tclearSelection();\n\t};\n\n\treturn { dispose, fitToView, clearSelection };\n}\n\nfunction setupControls(\n\tcamera: THREE.PerspectiveCamera,\n\tcanvas: HTMLCanvasElement,\n\tconfig: Required<ThreeInitializerOptions>\n): OrbitControls {\n\tconst controls = new OrbitControls(camera, canvas);\n\n\tconst target = config.camera.target;\n\tif (target) {\n\t\tcontrols.target.set(target.x, target.y, target.z);\n\t}\n\n\tcontrols.enableDamping = config.controls.enableDamping || false;\n\tcontrols.dampingFactor = config.controls.dampingFactor || 0.05;\n\n\tcontrols.autoRotate = config.controls.autoRotate || false;\n\tcontrols.autoRotateSpeed = config.controls.autoRotateSpeed || 0.5;\n\n\tcontrols.enableZoom = config.controls.enableZoom ?? true;\n\tcontrols.enablePan = config.controls.enablePan ?? true;\n\tcontrols.minDistance = config.controls.minDistance || 0.001;\n\tcontrols.maxDistance = config.controls.maxDistance || Infinity;\n\n\tcontrols.screenSpacePanning = false;\n\tcontrols.maxPolarAngle = Math.PI;\n\n\tcontrols.update();\n\treturn controls;\n}\n","import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { getLogger } from '@/core';\n\n// Camera configuration constants\nconst CAMERA_CONFIG = {\n\tHUGE_THRESHOLD: 10000,\n\tLARGE_THRESHOLD: 1000,\n\tSCALE_RATIO_THRESHOLD: 100,\n\tNEAR_PLANE_FACTOR: {\n\t\tTINY: 0.0001,\n\t\tSMALL: 0.001,\n\t\tNORMAL: 0.01\n\t},\n\tFAR_PLANE_FACTOR: {\n\t\tHUGE: 100,\n\t\tLARGE: 50,\n\t\tNORMAL: 20\n\t},\n\tINITIAL_DISTANCE_MULTIPLIER: 4\n};\n\n/**\n * Updates the scene with the given meshes and camera settings.\n * If initialPositionSet is false, it positions the camera and sets the controls target based on the bounding boxes of the meshes.\n * @param scene - The THREE.Scene object to update.\n * @param meshes - An array of THREE.Mesh objects to add to the scene.\n * @param camera - The THREE.PerspectiveCamera object to position.\n * @param controls - The OrbitControls object to update.\n * @param initialPositionSet - A boolean indicating whether the initial position of the camera and controls have been set.\n */\nexport function updateScene(\n\tscene: THREE.Scene,\n\tmeshes: THREE.Mesh[],\n\tcamera: THREE.PerspectiveCamera,\n\tcontrols: OrbitControls,\n\tinitialPositionSet: boolean\n) {\n\tclearScene(scene);\n\n\tif (meshes.length === 0) return;\n\n\t// Add new meshes to scene\n\tmeshes.forEach((mesh) => {\n\t\tscene.add(mesh);\n\t});\n\n\t// Calculate bounds of the new content\n\tconst unionBoundingBox = computeCombinedBoundingBox(meshes);\n\n\t// Get the center of the union bounding box\n\tconst center = unionBoundingBox.getCenter(new THREE.Vector3());\n\tconst size = unionBoundingBox.getSize(new THREE.Vector3());\n\n\t// Calculate a distance that is slightly larger than the largest dimension of the union bounding box\n\tconst maxDim = Math.max(size.x, size.y, size.z);\n\n\t// Always update camera frustum to ensure geometry is visible\n\t// This prevents clipping when geometry size changes significantly\n\tconst scaleRatio = maxDim / Math.min(size.x || 1, size.y || 1, size.z || 1);\n\n\tif (scaleRatio > CAMERA_CONFIG.SCALE_RATIO_THRESHOLD || maxDim > CAMERA_CONFIG.HUGE_THRESHOLD) {\n\t\t// Large scale range detected - use logarithmic depth buffer approach\n\t\tcamera.near = maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.TINY;\n\t\tcamera.far = maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.HUGE;\n\t} else if (maxDim > CAMERA_CONFIG.LARGE_THRESHOLD) {\n\t\t// Large scene\n\t\tcamera.near = maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.SMALL;\n\t\tcamera.far = maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.LARGE;\n\t} else {\n\t\t// Normal scene\n\t\tcamera.near = Math.max(0.01, maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.NORMAL);\n\t\tcamera.far = Math.max(2000, maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.NORMAL);\n\t}\n\n\tcamera.updateProjectionMatrix();\n\n\t// Only reposition camera and controls on first frame\n\tif (!initialPositionSet) {\n\t\tconst distance = maxDim * CAMERA_CONFIG.INITIAL_DISTANCE_MULTIPLIER;\n\n\t\tcamera.position.set(center.x + distance * 0.8, center.y + distance, center.z + distance * 1.2);\n\t\tcontrols.target.copy(center);\n\t\tcontrols.minDistance = camera.near * 2;\n\t\tcontrols.maxDistance = camera.far * 0.9;\n\n\t\tcontrols.update();\n\t} else {\n\t\t// Update control constraints to match new frustum\n\t\tcontrols.minDistance = camera.near * 2;\n\t\tcontrols.maxDistance = camera.far * 0.9;\n\t}\n}\n\n// =========================\n// Helper functions\n// =========================\n\n/**\n * Parses a color string in multiple formats to a THREE.Color object.\n * Supported formats:\n * - Hex: \"#C7A5A5\", \"C7A5A5\"\n * - RGB: \"199, 165, 165\"\n * - CSS named colors: \"red\", \"blue\", etc.\n * @param colorString - The color string to parse.\n * @returns A THREE.Color object.\n */\nexport function parseColor(colorString: string): THREE.Color {\n\tif (!colorString || typeof colorString !== 'string') {\n\t\tgetLogger().warn(`Invalid color input: ${colorString}, using white`);\n\t\treturn new THREE.Color(0xffffff);\n\t}\n\n\tconst trimmed = colorString.trim();\n\n\t// Try hex format (#C7A5A5 or C7A5A5) — require exactly 6 hex chars\n\tif (/^#?[0-9A-Fa-f]{6}$/.test(trimmed)) {\n\t\ttry {\n\t\t\tconst hex = trimmed.startsWith('#') ? trimmed : `#${trimmed}`;\n\t\t\treturn new THREE.Color(hex);\n\t\t} catch {\n\t\t\tgetLogger().warn(`Invalid hex color: ${colorString}, using white`);\n\t\t\treturn new THREE.Color(0xffffff);\n\t\t}\n\t}\n\n\t// Try RGB format (R, G, B)\n\tif (trimmed.includes(',')) {\n\t\tconst rgb = trimmed.split(',').map((c) => parseInt(c.trim(), 10));\n\t\tif (rgb.length === 3 && rgb.every((n) => !isNaN(n) && n >= 0 && n <= 255)) {\n\t\t\treturn new THREE.Color(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255);\n\t\t}\n\t}\n\n\t// Try CSS named color\n\ttry {\n\t\treturn new THREE.Color(trimmed.toLowerCase());\n\t} catch {\n\t\tgetLogger().warn(`Invalid color string: ${colorString}, using white`);\n\t\treturn new THREE.Color(0xffffff);\n\t}\n}\n\nexport function applyOffset(meshes: THREE.Mesh[], offsetY: number): void {\n\tmeshes.forEach((mesh) => {\n\t\tmesh.position.y -= offsetY;\n\t});\n}\n\n/**\n * Computes the combined world-axis-aligned bounding box of a set of meshes.\n * Correctly accounts for mesh transformations (rotation, position, scale).\n */\nexport function computeCombinedBoundingBox(meshes: THREE.Mesh[]): THREE.Box3 {\n\tconst combinedBoundingBox = new THREE.Box3();\n\tif (meshes.length === 0) return combinedBoundingBox;\n\tmeshes.forEach((mesh) => {\n\t\t// Ensure the world matrix is up to date before calculating the box\n\t\tmesh.updateMatrixWorld(true);\n\t\tconst bbox = new THREE.Box3().setFromObject(mesh);\n\t\tcombinedBoundingBox.union(bbox);\n\t});\n\treturn combinedBoundingBox;\n}\n\n/**\n * Clears the given THREE.Scene by removing all non-floor top-level children and\n * recursively disposing of their geometry and materials.\n *\n * Removes at the top level rather than traversing for meshes, so parent Groups\n * don't accumulate as ghost nodes after their mesh children are disposed.\n */\nfunction clearScene(scene: THREE.Scene): void {\n\t// Snapshot children — we mutate the array via removeFromParent during iteration\n\tconst topLevel = [...scene.children];\n\n\ttopLevel.forEach((object) => {\n\t\tif (object.userData.id === 'floor') return;\n\n\t\t// Recursively dispose all meshes in this subtree\n\t\tobject.traverse((child) => {\n\t\t\tif (!(child instanceof THREE.Mesh)) return;\n\n\t\t\tchild.geometry?.dispose();\n\n\t\t\tconst materials = Array.isArray(child.material) ? child.material : [child.material];\n\t\t\tmaterials.forEach((material) => {\n\t\t\t\t// Walk only own enumerable properties — `for...in` on a Three.js material\n\t\t\t\t// also iterates the prototype chain, which is needlessly expensive.\n\t\t\t\tfor (const value of Object.values(material)) {\n\t\t\t\t\tif (value instanceof THREE.Texture) {\n\t\t\t\t\t\tvalue.dispose();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmaterial.dispose();\n\t\t\t});\n\t\t});\n\n\t\tobject.removeFromParent();\n\t});\n}\n","import * as THREE from 'three';\n\nexport const EMISSIVE_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: 0x000000,\n\temissive: new THREE.Color(0xffffff),\n\temissiveIntensity: 5,\n\tmetalness: 0.0,\n\troughness: 0.2,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.2,\n\tdepthWrite: true,\n\tdepthTest: true,\n\ttransparent: false,\n\talphaTest: 0.0,\n\tpolygonOffset: true,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const METAL_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x000000),\n\tmetalness: 0.9,\n\troughness: 0.3,\n\tenvMapIntensity: 1.2,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.2,\n\treflectivity: 1,\n\tior: 2.5,\n\tthickness: 1,\n\tdepthWrite: true,\n\ttransparent: false,\n\talphaTest: 0.0,\n\tdepthTest: true,\n\tpolygonOffset: true,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const CONCRETE_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xcccccc),\n\tmetalness: 0.0,\n\troughness: 0.92,\n\tenvMapIntensity: 0.15,\n\tclearcoat: 0.05,\n\tclearcoatRoughness: 0.9,\n\treflectivity: 0.15,\n\ttransmission: 0.0,\n\tior: 1.45,\n\tthickness: 0.0,\n\tdepthWrite: true,\n\ttransparent: false,\n\talphaTest: 0.5,\n\tdepthTest: true,\n\tpolygonOffset: true,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const PLASTIC_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xffffff), // Default white plastic\n\tmetalness: 0.0,\n\troughness: 0.3,\n\tenvMapIntensity: 0.5,\n\tclearcoat: 0.5,\n\tclearcoatRoughness: 0.1,\n\treflectivity: 0.5,\n\tior: 1.4,\n\ttransmission: 0.0,\n\ttransparent: false,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tdithering: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const GLASS_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xffffff),\n\tmetalness: 0.0,\n\troughness: 0.0,\n\ttransmission: 0.95,\n\ttransparent: true,\n\topacity: 0.3,\n\tenvMapIntensity: 1.0,\n\tclearcoat: 1.0,\n\tclearcoatRoughness: 0.0,\n\tior: 1.52,\n\treflectivity: 0.9,\n\tthickness: 1.0,\n\tside: THREE.DoubleSide,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const RUBBER_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x1a1a1a),\n\tmetalness: 0.0,\n\troughness: 0.9,\n\tenvMapIntensity: 0.2,\n\tclearcoat: 0.1,\n\tclearcoatRoughness: 0.8,\n\treflectivity: 0.2,\n\tior: 1.3,\n\ttransmission: 0.0,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const WOOD_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x885533),\n\tmetalness: 0.0,\n\troughness: 0.7,\n\tenvMapIntensity: 0.3,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.4,\n\treflectivity: 0.3,\n\tior: 1.3,\n\ttransmission: 0.0,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tdithering: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n","import { decodeBase64ToBinary } from '@/core/utils/encoding';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport type { MaterialGroup, SerializableMaterial } from './types';\n\n// ============================================================================\n// WIRE FORMAT CONSTANTS\n// ============================================================================\n\n/** \"SLVA\" little-endian. */\nexport const BINARY_MESH_MAGIC = 0x41564c53;\n/** Bumped on any wire-layout change. */\nexport const BINARY_MESH_VERSION = 1;\n/** Bit 0 of the geometry flags word: 0 = int16 quantized, 1 = float32 raw. */\nexport const FLAG_FLOAT32 = 0x1;\n\nconst HEADER_PREAMBLE_BYTES = 4 /* magic */ + 4 /* version */ + 4; /* metadataLen */\nconst GEOMETRY_HEADER_BYTES =\n\t4 /* flags */ + 24 /* origin (3 x f64) */ + 24 /* scale (3 x f64) */ + 4; /* vertexCount */\n\n// ============================================================================\n// PARSED TYPES\n// ============================================================================\n\n/**\n * Metadata JSON embedded inside the binary blob.\n *\n * This is the same shape as a `MeshBatch` minus the `compressedData` field (the blob is opaque to\n * its own metadata header). Kept separate from the public `MeshBatch` type because the blob's\n * metadata never carries `compressedData` itself — it would be circular.\n */\nexport interface BinaryMeshMetadata {\n\tmaterials: SerializableMaterial[];\n\tgroups: MaterialGroup[];\n\tsourceComponentId?: string;\n}\n\n/**\n * Result of parsing a binary mesh blob.\n *\n * `vertices` and `indices` are typed-array views over the original `ArrayBuffer` — zero copies.\n * The consumer is responsible for not mutating the underlying buffer if it cares about safety,\n * or for calling `.slice()` to detach.\n */\nexport interface ParsedBinaryMeshBatch {\n\tmetadata: BinaryMeshMetadata;\n\tflags: number;\n\tvertices: Int16Array | Float32Array;\n\tindices: Uint32Array;\n\torigin: [number, number, number];\n\tscale: [number, number, number];\n}\n\n// ============================================================================\n// PARSER\n// ============================================================================\n\n/**\n * Parses a binary mesh batch blob in the SLVA wire format.\n *\n * The blob layout is:\n * ```\n * [4] magic = \"SLVA\" (0x53 0x4C 0x56 0x41)\n * [4] version = uint32 (currently 1)\n * [4] metadataLen = uint32 byte length of UTF-8 metadata JSON\n * [N] metadata = UTF-8 JSON (materials, groups, sourceComponentId, ...)\n * [4] flags = uint32 (bit 0: 0 = int16 quantized, 1 = float32 raw)\n * [24] origin = 3 x float64\n * [24] scale = 3 x float64 (step per int16 unit; identity for float32)\n * [4] vertexCount = uint32 number of vertices (positions = vertexCount * 3 components)\n * [V] vertices = int16[vertexCount*3] OR float32[vertexCount*3]\n * [4] indexCount = uint32 number of indices\n * [I] indices = uint32[indexCount]\n * ```\n *\n * For int16 vertices: world position = `origin + (q + 32767) * scale`. This matches Three.js\n * `BufferAttribute(arr, 3, true)` (`normalized: true`) semantics when the per-mesh transform\n * encodes `origin + scale`.\n *\n * For float32: `origin = (0, 0, 0)`, `scale = (1, 1, 1)`, vertices are raw world positions.\n *\n * @param input - The blob, as either an `ArrayBuffer`/`Uint8Array` (binary transport) or a\n * base64-encoded string (today's JSON-envelope transport).\n * @returns Decoded metadata plus typed-array views into the geometry payload.\n * @throws {RhinoComputeError} On invalid magic, unknown version, or truncated input.\n */\nexport function parseBinaryMeshBatch(\n\tinput: ArrayBuffer | Uint8Array | string\n): ParsedBinaryMeshBatch {\n\tconst bytes = toUint8Array(input);\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\n\tif (bytes.byteLength < HEADER_PREAMBLE_BYTES) {\n\t\tthrow fail('Blob too small to contain SLVA header.', {\n\t\t\texpectedBytes: HEADER_PREAMBLE_BYTES,\n\t\t\tavailableBytes: bytes.byteLength\n\t\t});\n\t}\n\n\tlet offset = 0;\n\n\tconst magic = view.getUint32(offset, true);\n\toffset += 4;\n\tif (magic !== BINARY_MESH_MAGIC) {\n\t\tthrow fail(`Invalid SLVA magic: 0x${magic.toString(16)}`, {\n\t\t\texpectedMagic: `0x${BINARY_MESH_MAGIC.toString(16)}`,\n\t\t\tactualMagic: `0x${magic.toString(16)}`\n\t\t});\n\t}\n\n\tconst version = view.getUint32(offset, true);\n\toffset += 4;\n\tif (version !== BINARY_MESH_VERSION) {\n\t\tthrow fail(`Unsupported SLVA version: ${version}`, {\n\t\t\texpectedVersion: BINARY_MESH_VERSION,\n\t\t\tactualVersion: version\n\t\t});\n\t}\n\n\tconst metadataLen = view.getUint32(offset, true);\n\toffset += 4;\n\tif (offset + metadataLen > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read metadata JSON.', {\n\t\t\texpectedBytes: metadataLen,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\n\tconst metadataBytes = bytes.subarray(offset, offset + metadataLen);\n\toffset += metadataLen;\n\n\tlet metadata: BinaryMeshMetadata;\n\ttry {\n\t\tmetadata = JSON.parse(decodeUtf8(metadataBytes)) as BinaryMeshMetadata;\n\t} catch (error) {\n\t\tthrow fail(\n\t\t\t`Failed to parse metadata JSON: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t{ metadataLen }\n\t\t);\n\t}\n\n\tif (offset + GEOMETRY_HEADER_BYTES > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read geometry header.', {\n\t\t\texpectedBytes: GEOMETRY_HEADER_BYTES,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\n\tconst flags = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst originX = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst originY = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst originZ = view.getFloat64(offset, true);\n\toffset += 8;\n\n\tconst scaleX = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleY = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleZ = view.getFloat64(offset, true);\n\toffset += 8;\n\n\tconst vertexCount = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst useFloat32 = (flags & FLAG_FLOAT32) !== 0;\n\tconst componentCount = vertexCount * 3;\n\tconst bytesPerComponent = useFloat32 ? 4 : 2;\n\tconst verticesByteLength = componentCount * bytesPerComponent;\n\n\tif (offset + verticesByteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read vertices.', {\n\t\t\texpectedBytes: verticesByteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tuseFloat32,\n\t\t\tvertexCount\n\t\t});\n\t}\n\n\t// Typed-array views require alignment to the element size. The header lays out the geometry\n\t// block such that the vertex byte offset is always 4-aligned (preamble 12 + metadataLen + 4 +\n\t// 48 + 4). float32 needs 4-byte alignment (satisfied), int16 needs 2-byte alignment\n\t// (satisfied). We can take a zero-copy view as long as `bytes.byteOffset + offset` agrees with\n\t// that alignment in the underlying buffer — a wrapper Uint8Array could violate it. Fall back\n\t// to a fresh copy if so.\n\tconst absoluteOffset = bytes.byteOffset + offset;\n\tconst verticesView = useFloat32\n\t\t? readFloat32Vertices(bytes.buffer, absoluteOffset, componentCount)\n\t\t: readInt16Vertices(bytes.buffer, absoluteOffset, componentCount);\n\toffset += verticesByteLength;\n\n\tif (offset + 4 > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read index count.', {\n\t\t\texpectedBytes: 4,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\tconst indexCount = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst indicesByteLength = indexCount * 4;\n\tif (offset + indicesByteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read indices.', {\n\t\t\texpectedBytes: indicesByteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tindexCount\n\t\t});\n\t}\n\n\tconst indicesView = readUint32Indices(bytes.buffer, bytes.byteOffset + offset, indexCount);\n\n\treturn {\n\t\tmetadata,\n\t\tflags,\n\t\tvertices: verticesView,\n\t\tindices: indicesView,\n\t\torigin: [originX, originY, originZ],\n\t\tscale: [scaleX, scaleY, scaleZ]\n\t};\n}\n\n// ============================================================================\n// HELPERS\n// ============================================================================\n\nfunction toUint8Array(input: ArrayBuffer | Uint8Array | string): Uint8Array {\n\tif (typeof input === 'string') {\n\t\treturn decodeBase64ToBinary(input);\n\t}\n\tif (input instanceof Uint8Array) {\n\t\treturn input;\n\t}\n\treturn new Uint8Array(input);\n}\n\nfunction decodeUtf8(bytes: Uint8Array): string {\n\tif (typeof TextDecoder !== 'undefined') {\n\t\treturn new TextDecoder('utf-8').decode(bytes);\n\t}\n\t// Node fallback (Buffer is utf-8 by default).\n\tif (\n\t\ttypeof (globalThis as { Buffer?: { from(b: Uint8Array): { toString(enc: string): string } } })\n\t\t\t.Buffer !== 'undefined'\n\t) {\n\t\treturn (\n\t\t\tglobalThis as { Buffer: { from(b: Uint8Array): { toString(enc: string): string } } }\n\t\t).Buffer.from(bytes).toString('utf-8');\n\t}\n\tthrow new RhinoComputeError(\n\t\t'No UTF-8 decoder available in this environment.',\n\t\tErrorCodes.INVALID_STATE\n\t);\n}\n\nfunction readInt16Vertices(buffer: ArrayBufferLike, byteOffset: number, count: number): Int16Array {\n\tif (count === 0) return new Int16Array(0);\n\tif (byteOffset % 2 === 0) {\n\t\treturn new Int16Array(buffer, byteOffset, count);\n\t}\n\t// Misaligned (rare — would require a wrapper Uint8Array with odd byteOffset).\n\tconst copy = new Uint8Array(count * 2);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 2));\n\treturn new Int16Array(copy.buffer);\n}\n\nfunction readFloat32Vertices(\n\tbuffer: ArrayBufferLike,\n\tbyteOffset: number,\n\tcount: number\n): Float32Array {\n\tif (count === 0) return new Float32Array(0);\n\tif (byteOffset % 4 === 0) {\n\t\treturn new Float32Array(buffer, byteOffset, count);\n\t}\n\tconst copy = new Uint8Array(count * 4);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 4));\n\treturn new Float32Array(copy.buffer);\n}\n\nfunction readUint32Indices(\n\tbuffer: ArrayBufferLike,\n\tbyteOffset: number,\n\tcount: number\n): Uint32Array {\n\tif (count === 0) return new Uint32Array(0);\n\tif (byteOffset % 4 === 0) {\n\t\treturn new Uint32Array(buffer, byteOffset, count);\n\t}\n\tconst copy = new Uint8Array(count * 4);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 4));\n\treturn new Uint32Array(copy.buffer);\n}\n\nfunction fail(message: string, context: Record<string, unknown>): RhinoComputeError {\n\treturn new RhinoComputeError(message, ErrorCodes.VALIDATION_ERROR, { context });\n}\n","import * as THREE from 'three';\n\nimport { parseColor } from '../threejs/three-helpers';\nimport { getLogger } from '@/core';\n\nimport { FLAG_FLOAT32, parseBinaryMeshBatch } from './binary-parser';\n\nimport type { ParsedBinaryMeshBatch } from './binary-parser';\nimport type { MeshBatch, MaterialGroup, SerializableMaterial } from './types';\n\n/**\n * Parses a batched mesh JSON and creates Three.js meshes.\n *\n * The geometry payload is the binary \"SLVA\" blob produced by the C# `BinaryGeometryWriter`,\n * base64-encoded into the outer JSON envelope. We `JSON.parse` the small envelope, then hand the\n * blob to `parseBinaryMeshBatch` which decodes the geometry without ever turning it into a string.\n *\n * @param batchJson - JSON string containing the batched mesh data\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n */\nexport async function parseMeshBatch(\n\tbatchJson: string,\n\toptions?: {\n\t\t/** Merge meshes with same material into single geometry*/\n\t\tmergeByMaterial?: boolean;\n\t\t/** Apply coordinate system transformations */\n\t\tapplyTransforms?: boolean;\n\t\t/** Enable performance monitoring */\n\t\tdebug?: boolean;\n\t}\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\tlet parseTime = 0;\n\n\ttry {\n\t\tconst parseStart = performance.now();\n\t\tconst batch: MeshBatch = JSON.parse(batchJson);\n\t\tparseTime = performance.now() - parseStart;\n\n\t\treturn await parseMeshBatchObject(batch, {\n\t\t\tmergeByMaterial,\n\t\t\tapplyTransforms,\n\t\t\tdebug,\n\t\t\tparseTime,\n\t\t\tperfStart\n\t\t});\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch:', error);\n\t\treturn [];\n\t}\n}\n\n/**\n * Parses a MeshBatch object and creates Three.js meshes.\n *\n * The path is synchronous internally — `parseBinaryMeshBatch` does no IO, just typed-array views\n * over the blob. The function stays `async` so callers don't have to change shape if we move\n * parsing into a worker later.\n *\n * @param batch - MeshBatch object\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n */\nexport async function parseMeshBatchObject(\n\tbatch: MeshBatch,\n\toptions?: {\n\t\t/** Merge meshes with same material into single geometry*/\n\t\tmergeByMaterial?: boolean;\n\t\t/** Apply coordinate system transformations */\n\t\tapplyTransforms?: boolean;\n\t\t/** Scale factor to apply to meshes (e.g., for unit conversion) */\n\t\tscaleFactor?: number;\n\t\t/** Enable performance monitoring */\n\t\tdebug?: boolean;\n\t\t/** Parse time (optional, for debugging) */\n\t\tparseTime?: number;\n\t\t/** Performance start time (optional, for debugging) */\n\t\tperfStart?: number;\n\t}\n): Promise<THREE.Mesh[]> {\n\tconst {\n\t\tmergeByMaterial = true,\n\t\tapplyTransforms = true,\n\t\tscaleFactor = 1,\n\t\tdebug = false,\n\t\tparseTime = 0,\n\t\tperfStart = debug ? performance.now() : 0\n\t} = options ?? {};\n\n\ttry {\n\t\tconst decodeStart = performance.now();\n\t\tconst parsed = parseBinaryMeshBatch(batch.compressedData);\n\t\tconst decodeTime = performance.now() - decodeStart;\n\n\t\tconst blobBytes = debug ? approximateBase64DecodedBytes(batch.compressedData) : 0;\n\n\t\treturn buildMeshesFromParsed(parsed, {\n\t\t\tmergeByMaterial,\n\t\t\tapplyTransforms,\n\t\t\tscaleFactor,\n\t\t\tdebug,\n\t\t\tparseTime,\n\t\t\tdecodeTime,\n\t\t\tperfStart,\n\t\t\tblobBytes,\n\t\t\tfallback: {\n\t\t\t\tmaterials: batch.materials,\n\t\t\t\tgroups: batch.groups,\n\t\t\t\tsourceComponentId: batch.sourceComponentId\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch object:', error);\n\t\treturn [];\n\t}\n}\n\n/**\n * Parses a raw binary mesh batch blob (SLVA wire format) and creates Three.js meshes.\n *\n * Use this entry point when the blob arrives as a binary WebSocket frame (Phase 1b transport):\n * the JSON envelope no longer carries `displayData`, so there's nothing to `JSON.parse`. The blob\n * is self-describing — materials, groups, and `sourceComponentId` come from its embedded metadata\n * header.\n *\n * @param blob - Raw blob bytes from a binary WebSocket frame.\n * @param options - Rendering options.\n * @returns Promise resolving to array of Three.js mesh objects.\n */\nexport async function parseMeshBatchBlob(\n\tblob: ArrayBuffer | Uint8Array,\n\toptions?: {\n\t\t/** Merge meshes with same material into single geometry */\n\t\tmergeByMaterial?: boolean;\n\t\t/** Apply coordinate system transformations */\n\t\tapplyTransforms?: boolean;\n\t\t/** Scale factor to apply to meshes (e.g., for unit conversion) */\n\t\tscaleFactor?: number;\n\t\t/** Enable performance monitoring */\n\t\tdebug?: boolean;\n\t}\n): Promise<THREE.Mesh[]> {\n\tconst {\n\t\tmergeByMaterial = true,\n\t\tapplyTransforms = true,\n\t\tscaleFactor = 1,\n\t\tdebug = false\n\t} = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\n\ttry {\n\t\tconst decodeStart = performance.now();\n\t\tconst parsed = parseBinaryMeshBatch(blob);\n\t\tconst decodeTime = performance.now() - decodeStart;\n\n\t\tconst blobBytes = blob instanceof Uint8Array ? blob.byteLength : blob.byteLength;\n\n\t\treturn buildMeshesFromParsed(parsed, {\n\t\t\tmergeByMaterial,\n\t\t\tapplyTransforms,\n\t\t\tscaleFactor,\n\t\t\tdebug,\n\t\t\tparseTime: 0,\n\t\t\tdecodeTime,\n\t\t\tperfStart,\n\t\t\tblobBytes\n\t\t});\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch blob:', error);\n\t\treturn [];\n\t}\n}\n\ninterface BuildOptions {\n\tmergeByMaterial: boolean;\n\tapplyTransforms: boolean;\n\tscaleFactor: number;\n\tdebug: boolean;\n\tparseTime: number;\n\tdecodeTime: number;\n\tperfStart: number;\n\tblobBytes: number;\n\t/** Outer-envelope fallback when the blob's metadata is missing fields (defensive). */\n\tfallback?: {\n\t\tmaterials?: SerializableMaterial[];\n\t\tgroups?: MaterialGroup[];\n\t\tsourceComponentId?: string;\n\t};\n}\n\nfunction buildMeshesFromParsed(\n\tparsed: ParsedBinaryMeshBatch,\n\topts: BuildOptions\n): Promise<THREE.Mesh[]> {\n\tconst {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tscaleFactor,\n\t\tdebug,\n\t\tparseTime,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes,\n\t\tfallback\n\t} = opts;\n\n\tconst materialsSrc = parsed.metadata.materials ?? fallback?.materials ?? [];\n\tconst groups = parsed.metadata.groups ?? fallback?.groups ?? [];\n\tconst sourceComponentId = parsed.metadata.sourceComponentId ?? fallback?.sourceComponentId;\n\n\tconst isFloat32 = (parsed.flags & FLAG_FLOAT32) !== 0;\n\n\t// Dequantize once up-front into a single Float32Array. Downstream code (per-group merging,\n\t// computeVertexNormals, ground-offset, scaleFactor) all expect world-unit floats, and a single\n\t// linear pass over the int16 buffer is far cheaper than the legacy gunzip + base64 path. The\n\t// Z-up -> Y-up rotation, when requested, is folded into the same pass.\n\tconst worldVertices = isFloat32\n\t\t? maybeRotateFloat32Vertices(parsed.vertices as Float32Array, applyTransforms)\n\t\t: dequantizeInt16(\n\t\t\t\tparsed.vertices as Int16Array,\n\t\t\t\tparsed.origin,\n\t\t\t\tparsed.scale,\n\t\t\t\tapplyTransforms\n\t\t\t);\n\n\tif (debug) {\n\t\tconst wireBytes = parsed.vertices.byteLength + parsed.indices.byteLength;\n\t\tgetLogger().debug('Mesh Batch Stats:');\n\t\tgetLogger().debug(` Materials: ${materialsSrc.length} | Groups: ${groups.length}`);\n\t\tgetLogger().debug(\n\t\t\t` Vertices: ${parsed.vertices.length / 3} | Indices: ${parsed.indices.length}`\n\t\t);\n\t\tgetLogger().debug(` Format: ${isFloat32 ? 'float32' : 'int16 quantized'}`);\n\t\tgetLogger().debug(\n\t\t\t` Blob: ${(blobBytes / 1024 / 1024).toFixed(2)} MB | Geometry on wire: ${(wireBytes / 1024 / 1024).toFixed(2)} MB`\n\t\t);\n\t}\n\n\tconst meshCreateStart = performance.now();\n\tconst materials = materialsSrc.map(createMaterial);\n\n\tconst meshes: THREE.Mesh[] = [];\n\n\tfor (const group of groups) {\n\t\tif (mergeByMaterial && group.meshes.length > 1) {\n\t\t\tconst mergedMesh = createMergedMesh(group, worldVertices, parsed.indices, materials);\n\t\t\tmergedMesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\tmeshes.push(mergedMesh);\n\t\t} else {\n\t\t\tconst individualMeshes = createIndividualMeshes(\n\t\t\t\tgroup,\n\t\t\t\tworldVertices,\n\t\t\t\tparsed.indices,\n\t\t\t\tmaterials\n\t\t\t);\n\t\t\tfor (const mesh of individualMeshes) {\n\t\t\t\tmesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\t}\n\t\t\tmeshes.push(...individualMeshes);\n\t\t}\n\t}\n\n\tif (scaleFactor !== 1) {\n\t\tfor (const mesh of meshes) {\n\t\t\tmesh.scale.set(scaleFactor, scaleFactor, scaleFactor);\n\t\t}\n\t}\n\n\tconst meshCreateTime = performance.now() - meshCreateStart;\n\n\tif (debug) {\n\t\tconst totalTime = performance.now() - perfStart;\n\t\tgetLogger().debug('Performance:');\n\t\tif (parseTime > 0) getLogger().debug(` Parse JSON: ${parseTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Decode binary: ${decodeTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Create Meshes: ${meshCreateTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Total: ${totalTime.toFixed(2)}ms`);\n\t}\n\n\treturn Promise.resolve(meshes);\n}\n\n// ============================================================================\n// DEQUANTIZATION\n// ============================================================================\n\n/**\n * Reconstructs world-unit float32 positions from int16 quantized values.\n *\n * Mirrors the encoder formula: `world = origin + (q + 32767) * scale`. When\n * `applyCoordinateTransform=true` we fold the Rhino Z-up -> Three Y-up shuffle into the same pass\n * (`(x, y, z) -> (x, z, -y)`), saving a second walk over the buffer.\n */\nfunction dequantizeInt16(\n\tq: Int16Array,\n\torigin: [number, number, number],\n\tscale: [number, number, number],\n\tapplyCoordinateTransform: boolean\n): Float32Array {\n\tconst out = new Float32Array(q.length);\n\tconst ox = origin[0];\n\tconst oy = origin[1];\n\tconst oz = origin[2];\n\tconst sx = scale[0];\n\tconst sy = scale[1];\n\tconst sz = scale[2];\n\n\tif (applyCoordinateTransform) {\n\t\t// Rotate -90 deg around X: (x, y, z) -> (x, z, -y)\n\t\tfor (let i = 0; i < q.length; i += 3) {\n\t\t\tconst wx = ox + (q[i]! + 32767) * sx;\n\t\t\tconst wy = oy + (q[i + 1]! + 32767) * sy;\n\t\t\tconst wz = oz + (q[i + 2]! + 32767) * sz;\n\t\t\tout[i] = wx;\n\t\t\tout[i + 1] = wz;\n\t\t\tout[i + 2] = -wy;\n\t\t}\n\t} else {\n\t\tfor (let i = 0; i < q.length; i += 3) {\n\t\t\tout[i] = ox + (q[i]! + 32767) * sx;\n\t\t\tout[i + 1] = oy + (q[i + 1]! + 32767) * sy;\n\t\t\tout[i + 2] = oz + (q[i + 2]! + 32767) * sz;\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * For float32 batches: when no transform is needed we can pass through the parser's view; the\n * caller doesn't mutate it. When the rotation is needed we have to allocate.\n */\nfunction maybeRotateFloat32Vertices(\n\tvertices: Float32Array,\n\tapplyCoordinateTransform: boolean\n): Float32Array {\n\tif (!applyCoordinateTransform) return vertices;\n\n\tconst out = new Float32Array(vertices.length);\n\tfor (let i = 0; i < vertices.length; i += 3) {\n\t\tconst x = vertices[i]!;\n\t\tconst y = vertices[i + 1]!;\n\t\tconst z = vertices[i + 2]!;\n\t\tout[i] = x;\n\t\tout[i + 1] = z;\n\t\tout[i + 2] = -y;\n\t}\n\treturn out;\n}\n\n// ============================================================================\n// MATERIAL CONSTRUCTION\n// ============================================================================\n\nfunction createMaterial(matData: SerializableMaterial): THREE.MeshPhysicalMaterial {\n\tconst color = parseColor(matData.color);\n\n\treturn new THREE.MeshPhysicalMaterial({\n\t\tcolor,\n\t\tmetalness: matData.metalness,\n\t\troughness: matData.roughness,\n\t\topacity: matData.opacity,\n\t\ttransparent: matData.transparent,\n\t\tside: THREE.DoubleSide,\n\t\t// Reduced polygon offset to minimize artifacts\n\t\t// Only use minimal offset to prevent z-fighting on coplanar faces\n\t\tpolygonOffset: true,\n\t\tpolygonOffsetFactor: 0.5,\n\t\tpolygonOffsetUnits: 0.5,\n\t\t// Improve depth rendering\n\t\tdepthWrite: true,\n\t\tdepthTest: true\n\t});\n}\n\n// ============================================================================\n// MESH CONSTRUCTION\n// ============================================================================\n\n/**\n * Creates a merged mesh from multiple meshes sharing the same material.\n *\n * Indices in the parser output already reference offsets into the combined vertex array (the C#\n * pipeline rebases per-mesh local indices into combined-array indices when assembling the batch).\n * For merged meshes we copy the relevant slices into a fresh contiguous buffer and shift indices\n * to match the new layout.\n */\nfunction createMergedMesh(\n\tgroup: MaterialGroup,\n\tallVertices: Float32Array,\n\tallIndices: Uint32Array,\n\tmaterials: THREE.Material[]\n): THREE.Mesh {\n\tlet totalVertexCount = 0;\n\tlet totalIndexCount = 0;\n\tfor (const meshMeta of group.meshes) {\n\t\ttotalVertexCount += meshMeta.vertexCount;\n\t\ttotalIndexCount += meshMeta.indexCount;\n\t}\n\n\tconst mergedVertices = new Float32Array(totalVertexCount * 3);\n\tconst mergedIndices = new Uint32Array(totalIndexCount);\n\n\tlet vertexWriteCursor = 0;\n\tlet indexWriteCursor = 0;\n\n\tfor (const meshMeta of group.meshes) {\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentLen = meshMeta.vertexCount * 3;\n\t\tmergedVertices.set(\n\t\t\tallVertices.subarray(componentStart, componentStart + componentLen),\n\t\t\tvertexWriteCursor * 3\n\t\t);\n\n\t\tconst indicesSlice = allIndices.subarray(\n\t\t\tmeshMeta.indexStart,\n\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t);\n\t\tconst indexShift = vertexWriteCursor - meshMeta.vertexStart;\n\t\tif (indexShift === 0) {\n\t\t\tmergedIndices.set(indicesSlice, indexWriteCursor);\n\t\t} else {\n\t\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\t\tmergedIndices[indexWriteCursor + i] = indicesSlice[i]! + indexShift;\n\t\t\t}\n\t\t}\n\n\t\tvertexWriteCursor += meshMeta.vertexCount;\n\t\tindexWriteCursor += meshMeta.indexCount;\n\t}\n\n\tconst geometry = new THREE.BufferGeometry();\n\tgeometry.setAttribute('position', new THREE.BufferAttribute(mergedVertices, 3));\n\tgeometry.setIndex(new THREE.BufferAttribute(mergedIndices, 1));\n\tgeometry.computeVertexNormals();\n\n\tconst threeMesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\tconst firstMesh = group.meshes[0];\n\tconst meshNames = group.meshes.map((m) => m.name).filter((name) => name && name.length > 0);\n\tthreeMesh.name = meshNames.length > 0 ? meshNames[0]! : `merged_material_${group.materialId}`;\n\tthreeMesh.castShadow = true;\n\tthreeMesh.receiveShadow = true;\n\n\tthreeMesh.userData = {\n\t\tname: threeMesh.name,\n\t\tlayer: firstMesh?.layer ?? '',\n\t\toriginalIndex: firstMesh?.originalIndex ?? 0,\n\t\tmetadata: firstMesh?.metadata ?? {},\n\t\tmergedFrom: group.meshes.slice(1).map((m) => ({\n\t\t\tname: m.name,\n\t\t\tlayer: m.layer,\n\t\t\toriginalIndex: m.originalIndex\n\t\t}))\n\t};\n\n\treturn threeMesh;\n}\n\n/**\n * Creates individual meshes from a material group. Each mesh's indices are rebased so they\n * address its own local vertex slice starting from 0.\n */\nfunction createIndividualMeshes(\n\tgroup: MaterialGroup,\n\tallVertices: Float32Array,\n\tallIndices: Uint32Array,\n\tmaterials: THREE.Material[]\n): THREE.Mesh[] {\n\tconst meshes: THREE.Mesh[] = [];\n\n\tfor (const meshMeta of group.meshes) {\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentLen = meshMeta.vertexCount * 3;\n\n\t\t// `subarray` returns a view; copy via `slice` so the BufferAttribute owns its memory and\n\t\t// downstream code (dispose/reuse) can't surprise us by sharing the parser's buffer.\n\t\tconst vertices = allVertices.slice(componentStart, componentStart + componentLen);\n\n\t\tconst indicesSlice = allIndices.subarray(\n\t\t\tmeshMeta.indexStart,\n\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t);\n\t\tconst rebasedIndices = new Uint32Array(indicesSlice.length);\n\t\tconst baseIndex = meshMeta.vertexStart;\n\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\trebasedIndices[i] = indicesSlice[i]! - baseIndex;\n\t\t}\n\n\t\tconst geometry = new THREE.BufferGeometry();\n\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));\n\t\tgeometry.setIndex(new THREE.BufferAttribute(rebasedIndices, 1));\n\t\tgeometry.computeVertexNormals();\n\n\t\tconst mesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\t\tmesh.name = meshMeta.name;\n\t\tmesh.userData = {\n\t\t\tname: meshMeta.name,\n\t\t\tlayer: meshMeta.layer ?? '',\n\t\t\toriginalIndex: meshMeta.originalIndex,\n\t\t\tmetadata: meshMeta.metadata ?? {}\n\t\t};\n\t\tmesh.castShadow = true;\n\t\tmesh.receiveShadow = true;\n\n\t\tmeshes.push(mesh);\n\t}\n\n\treturn meshes;\n}\n\n// ============================================================================\n// DEBUG HELPERS\n// ============================================================================\n\nfunction approximateBase64DecodedBytes(base64: string): number {\n\treturn Math.floor((base64.length * 3) / 4);\n}\n","import * as THREE from 'three';\n\nimport { applyOffset, computeCombinedBoundingBox } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\n\nimport { parseMeshBatch } from './batch-parser';\n\nimport type { DataItem, GrasshopperComputeResponse } from '@/features/grasshopper/types';\nimport type { MeshExtractionOptions, MeshBatchParsingOptions } from './types';\n\n// Constants\nexport const SCALE_FACTORS: Record<string, number> = {\n\tMillimeters: 1 / 1000,\n\tCentimeters: 1 / 100,\n\tMeters: 1,\n\tInches: 1 / 39.37,\n\tFeet: 1 / 3.28084\n};\n\nconst DISPLAY_COMPONENT_TYPE = 'Display';\n\n/**\n * Extracts and processes display meshes from a ComputePointerResponse using the Grasshopper WebDisplay component.\n *\n * This is the primary entry point for extracting mesh geometry from Grasshopper compute responses.\n * It handles all aspects of mesh processing: decompression, coordinate transformation, scaling, and positioning.\n *\n * **Note:** Mesh decompression happens asynchronously in a Web Worker to prevent UI blocking.\n *\n * @param data - The ComputePointerResponse containing Grasshopper output trees.\n * @param options - Configuration for mesh extraction and parsing behavior. All options are optional with sensible defaults.\n * @returns Promise resolving to array of THREE.Mesh objects (may be empty).\n * @throws Rethrows unexpected errors after attempting to dispose any created meshes.\n *\n * @remarks\n * - Only works with the WebDisplay component of GHHeadless.\n * - Requires changes to Rhino.Compute (see https://github.com/TheVessen/compute.rhino3d).\n * - Provides a performant way to display mesh data in Three.js.\n * - Decompression is performed in a Web Worker for non-blocking UI updates.\n * - Supports mesh metadata (names, user data) if provided in the compute response.\n *\n * @internal Internal helper: high-level extraction remains public via visualization module, but this\n * function is considered internal implementation detail for mesh extraction.\n *\n * @example\n * ```ts\n * // Simple usage with defaults (all processing enabled)\n * const meshes = await getThreeMeshesFromComputeResponse(response);\n *\n * // With debugging enabled\n * const meshes = await getThreeMeshesFromComputeResponse(response, { debug: true });\n *\n * // With advanced options\n * const meshes = await getThreeMeshesFromComputeResponse(response, {\n * debug: true,\n * allowScaling: true,\n * allowAutoPosition: false,\n * parsing: {\n * mergeByMaterial: false,\n * applyTransforms: true,\n * debug: true,\n * },\n * });\n * ```\n */\nexport async function getThreeMeshesFromComputeResponse(\n\tdata: GrasshopperComputeResponse,\n\toptions?: MeshExtractionOptions\n): Promise<THREE.Mesh[]> {\n\tconst startTime = performance.now();\n\tconst meshes: THREE.Mesh[] = [];\n\n\tconst {\n\t\tallowScaling = true,\n\t\tallowAutoPosition = true,\n\t\tdebug = false,\n\t\tparsing: parsingOptions = {}\n\t} = options ?? {};\n\n\ttry {\n\t\tconst scaleFactor = allowScaling ? getScaleFactor(data.modelunits) : 1;\n\t\tawait extractMeshesFromData(data, meshes, scaleFactor, parsingOptions, debug);\n\n\t\tif (allowAutoPosition) {\n\t\t\tapplyGroundOffset(meshes);\n\t\t}\n\n\t\treturn meshes;\n\t} catch (error) {\n\t\thandleError(error, meshes);\n\t\tthrow error;\n\t} finally {\n\t\tif (debug) {\n\t\t\tlogProcessingTime(startTime);\n\t\t}\n\t}\n}\n\n/**\n * Gets the scale factor for the given unit type.\n */\nfunction getScaleFactor(modelUnits: string): number {\n\treturn SCALE_FACTORS[modelUnits] ?? 1;\n}\n\n/**\n * Extracts meshes from compute response data.\n */\nasync function extractMeshesFromData(\n\tdata: GrasshopperComputeResponse,\n\tmeshes: THREE.Mesh[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const value of data.values) {\n\t\tconst innerTree = value.InnerTree as { [key: string]: DataItem[] };\n\n\t\tfor (const path in innerTree) {\n\t\t\tconst branch = innerTree[path];\n\t\t\tif (!branch) continue;\n\n\t\t\tawait processDataBranch(branch, meshes, scaleFactor, parsingOptions, debug);\n\t\t}\n\t}\n}\n\n/**\n * Processes a single data branch to extract MeshBatch display meshes.\n */\nasync function processDataBranch(\n\tbranch: DataItem[],\n\tmeshes: THREE.Mesh[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const item of branch) {\n\t\tif (item.type.includes(DISPLAY_COMPONENT_TYPE)) {\n\t\t\tconst mergedParsingOptions = {\n\t\t\t\tmergeByMaterial: true,\n\t\t\t\tapplyTransforms: true,\n\t\t\t\tdebug: false,\n\t\t\t\t...parsingOptions\n\t\t\t};\n\n\t\t\tconst batchMeshes = await parseMeshBatch(item.data, mergedParsingOptions);\n\n\t\t\tif (scaleFactor !== 1) {\n\t\t\t\tfor (const mesh of batchMeshes) {\n\t\t\t\t\tmesh.scale.set(scaleFactor, scaleFactor, scaleFactor);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmeshes.push(...batchMeshes);\n\n\t\t\tif (debug) {\n\t\t\t\tgetLogger().debug(`Extracted ${batchMeshes.length} meshes from batch`);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Applies vertical offset to position meshes on the Z=0 plane.\n */\nfunction applyGroundOffset(meshes: THREE.Mesh[]): void {\n\tif (meshes.length === 0) return;\n\n\tconst combinedBoundingBox = computeCombinedBoundingBox(meshes);\n\tconst offsetY = combinedBoundingBox.min.y;\n\tapplyOffset(meshes, offsetY);\n}\n\n/**\n * Handles errors by disposing created meshes and logging.\n */\nfunction handleError(error: unknown, meshes: THREE.Mesh[]): void {\n\tgetLogger().error('An unexpected error occurred:', error);\n\tdisposeMeshes(meshes);\n}\n\n/**\n * Disposes of all meshes and their associated resources.\n */\nfunction disposeMeshes(meshes: THREE.Mesh[]): void {\n\tfor (const mesh of meshes) {\n\t\tif (mesh.geometry) {\n\t\t\tmesh.geometry.dispose();\n\t\t}\n\n\t\tif (mesh.material) {\n\t\t\tif (Array.isArray(mesh.material)) {\n\t\t\t\tmesh.material.forEach((material) => material.dispose());\n\t\t\t} else {\n\t\t\t\tmesh.material.dispose();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Logs the processing time for mesh extraction.\n */\nfunction logProcessingTime(startTime: number): void {\n\tconst elapsed = performance.now() - startTime;\n\tgetLogger().info('Time to process meshes:', `${elapsed.toFixed(2)}ms`);\n}\n"],"mappings":"sGAAA,UAAYA,MAAW,QACvB,OAAS,iBAAAC,OAAqB,yCAC9B,OAAS,aAAAC,OAAiB,oCAK1B,IAAMC,EAAY,IAAU,UAAQ,EAAG,EAAG,CAAC,EAGrCC,EAAgB,CAACC,EAAeC,EAAeC,EAAeC,IAAyB,CAC5F,OAAQH,EAAO,CACd,IAAK,KACJ,OAAOC,EACR,IAAK,KACJ,OAAOC,EACR,QACC,OAAOC,CACT,CACD,EAKaC,GAAY,SACxBC,EACAC,EASC,CACD,IAAMC,EAASC,GAAcF,GAAW,CAAC,CAAC,EAEpCG,EAAQC,GAAYH,CAAM,EAC1BI,EAASC,GAAaL,EAAQF,CAAM,EACpCQ,EAAWC,GAAcT,EAAQE,CAAM,EACvCQ,EAAWC,GAAcL,EAAQN,EAAQE,CAAM,EAErDU,GAAiBR,EAAOF,CAAM,EAC9BW,GAAcT,EAAOF,CAAM,E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AM,QAAQA,EAAK,QAAQ,EAC9BA,EAAK,SAAS,QAASM,GAAaA,EAAS,QAAQ,CAAC,EAEtDN,EAAK,SAAS,QAAQ,EAI1B,CAKA,SAASX,GAAkBZ,EAAyB,CACnD,IAAM8B,EAAU,YAAY,IAAI,EAAI9B,EACpCwB,EAAU,EAAE,KAAK,0BAA2B,GAAGM,EAAQ,QAAQ,CAAC,CAAC,IAAI,CACtE","names":["THREE","OrbitControls","HDRLoader","defaultUp","getScaleValue","scale","mmVal","cmVal","mVal","initThree","canvas","options","config","applyDefaults","scene","createScene","camera","createCamera","renderer","setupRenderer","controls","setupControls","setupEnvironment","setupLighting","addFloor","eventHandlers","setupEventHandlers","parent","getCanvasSize","animate","disposeAnimation","createAnimationLoop","sceneUp","object","material","defaults","bgColor","animateCameraTo","toPosition","toTarget","durationMs","fromPosition","fromTarget","startTime","easeOut","t","tick","elapsed","onFrame","animationId","lastTime","checkResize","width","height","pixelRatio","newW","newH","now","delta","HDRLoader","envMap","error","getLogger","ambientLight","sunlight","pos","shadowSize","shadowNear","shadowFar","floorSize","floorGeometry","floorColor","floorMaterial","floor","selectedObjects","originalMaterials","raycaster","mouse","mouseDownPosition","isFullyVisible","current","fitToView","box","center","size","maxDim","fov","distance","direction","selectionColorObj","clearSelection","obj","handleMouseDown","event","handleCanvasClick","currentMousePosition","rect","intersects","i","clickedObject","clonedMaterial","handleDoubleClick","target","targetPosition","handleKeydown","OrbitControls","THREE","CAMERA_CONFIG","updateScene","scene","meshes","camera","controls","initialPositionSet","clearScene","mesh","unionBoundingBox","computeCombinedBoundingBox","center","size","maxDim","distance","parseColor","colorString","getLogger","trimmed","hex","rgb","c","n","applyOffset","offsetY","combinedBoundingBox","bbox","object","child","material","value","three_materials_exports","__export","CONCRETE_MATERIAL","EMISSIVE_MATERIAL","GLASS_MATERIAL","METAL_MATERIAL","PLASTIC_MATERIAL","RUBBER_MATERIAL","WOOD_MATERIAL","THREE","BINARY_MESH_MAGIC","BINARY_MESH_VERSION","FLAG_FLOAT32","HEADER_PREAMBLE_BYTES","GEOMETRY_HEADER_BYTES","parseBinaryMeshBatch","input","bytes","toUint8Array","view","fail","offset","magic","version","metadataLen","metadataBytes","metadata","decodeUtf8","error","flags","originX","originY","originZ","scaleX","scaleY","scaleZ","vertexCount","useFloat32","componentCount","verticesByteLength","absoluteOffset","verticesView","readFloat32Vertices","readInt16Vertices","indexCount","indicesByteLength","indicesView","readUint32Indices","decodeBase64ToBinary","RhinoComputeError","ErrorCodes","buffer","byteOffset","count","copy","message","context","THREE","parseMeshBatch","batchJson","options","mergeByMaterial","applyTransforms","debug","perfStart","parseTime","parseStart","batch","parseMeshBatchObject","error","getLogger","scaleFactor","decodeStart","parsed","parseBinaryMeshBatch","decodeTime","blobBytes","approximateBase64DecodedBytes","buildMeshesFromParsed","parseMeshBatchBlob","blob","opts","fallback","materialsSrc","groups","sourceComponentId","isFloat32","FLAG_FLOAT32","worldVertices","maybeRotateFloat32Vertices","dequantizeInt16","wireBytes","meshCreateStart","materials","createMaterial","meshes","group","mergedMesh","createMergedMesh","individualMeshes","createIndividualMeshes","mesh","meshCreateTime","totalTime","q","origin","scale","applyCoordinateTransform","out","ox","oy","oz","sx","sy","sz","i","wx","wy","wz","vertices","x","y","z","matData","color","parseColor","allVertices","allIndices","totalVertexCount","totalIndexCount","meshMeta","mergedVertices","mergedIndices","vertexWriteCursor","indexWriteCursor","componentStart","componentLen","indicesSlice","indexShift","geometry","threeMesh","firstMesh","meshNames","m","name","rebasedIndices","baseIndex","base64","SCALE_FACTORS","DISPLAY_COMPONENT_TYPE","getThreeMeshesFromComputeResponse","data","options","startTime","meshes","allowScaling","allowAutoPosition","debug","parsingOptions","scaleFactor","getScaleFactor","extractMeshesFromData","applyGroundOffset","error","handleError","logProcessingTime","modelUnits","value","innerTree","path","branch","processDataBranch","item","mergedParsingOptions","batchMeshes","parseMeshBatch","mesh","getLogger","offsetY","computeCombinedBoundingBox","applyOffset","disposeMeshes","material","elapsed"]}
|
package/dist/chunk-OW6HV6QP.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{c as n,d as a}from"./chunk-XBIEAJBK.js";function f(e){return Buffer.from(e,"utf-8").toString("base64")}function s(e){return!e||e.length<2||e.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(e)}function l(e){if(typeof globalThis.Buffer=="function"){let t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof globalThis.atob=="function"){let t=globalThis.atob(e),o=new Uint8Array(t.length);for(let r=0;r<t.length;r++)o[r]=t.charCodeAt(r)&255;return o}throw new a("Base64 decoding not supported in this environment.",n.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function c(e){if(typeof globalThis.Buffer=="function")return globalThis.Buffer.from(e).toString("base64");if(typeof globalThis.btoa=="function"){let o="";for(let r=0;r<e.length;r+=32768)o+=String.fromCharCode.apply(null,Array.from(e.subarray(r,r+32768)));return globalThis.btoa(o)}throw new a("Base64 encoding not supported in this environment.",n.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}export{f as a,s as b,l as c,c as d};
|
|
2
|
-
//# sourceMappingURL=chunk-OW6HV6QP.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/utils/encoding.ts"],"sourcesContent":["import { RhinoComputeError, ErrorCodes } from '../errors';\nimport { getLogger } from './logger';\n\n/**\n * Encodes a string to base64 (Node 20+ safe)\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param str - String to encode\n * @returns Base64 encoded string\n */\nexport function encodeStringToBase64(str: string): string {\n\treturn Buffer.from(str, 'utf-8').toString('base64');\n}\n\n/**\n * Decodes a base64 string to a UTF-8 string (Node 20+ safe)\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param base64Str - Base64 encoded string\n * @returns Decoded UTF-8 string\n */\nexport function decodeBase64ToString(base64Str: string): string {\n\treturn Buffer.from(base64Str, 'base64').toString('utf-8');\n}\n\n/**\n * Checks if a string is valid base64\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param str - String to check\n * @returns True if the string is valid base64\n */\nexport function isBase64(str: string): boolean {\n\tif (!str || str.length < 2) return false;\n\t// Length must be a multiple of 4, only alphabet chars + at most 2 trailing '='\n\tif (str.length % 4 !== 0) return false;\n\treturn /^[A-Za-z0-9+/]+={0,2}$/.test(str);\n}\n\n/**\n * Decodes a base64 string to binary data (Uint8Array)\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * @param base64File - Base64 encoded string\n * @returns Decoded binary data as Uint8Array\n * @throws {RhinoComputeError} If base64 decoding is not supported in this environment.\n */\nexport function decodeBase64ToBinary(base64File: string): Uint8Array {\n\t// Prefer Buffer in Node — it's faster and avoids the latin-1 string detour\n\t// that atob + charCodeAt requires.\n\tif (typeof (globalThis as any).Buffer === 'function') {\n\t\tconst buf = (globalThis as any).Buffer.from(base64File, 'base64');\n\t\treturn new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\t}\n\tif (typeof globalThis.atob === 'function') {\n\t\tconst binary = globalThis.atob(base64File);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i) & 0xff;\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tthrow new RhinoComputeError(\n\t\t'Base64 decoding not supported in this environment.',\n\t\tErrorCodes.INVALID_STATE,\n\t\t{ context: { environmentInfo: 'atob or Buffer not available' } }\n\t);\n}\n\n/**\n * Encodes binary data (Uint8Array) to base64 string.\n *\n * @internal Internal encoding helper — kept internal to `@selvajs/compute`.\n *\n * Uses Node's `Buffer` when available (faster, single allocation) and falls\n * back to `btoa` over a latin-1 string in browsers/workers.\n */\nexport function base64ByteArray(bytes: Uint8Array): string {\n\tif (typeof (globalThis as any).Buffer === 'function') {\n\t\treturn (globalThis as any).Buffer.from(bytes).toString('base64');\n\t}\n\tif (typeof globalThis.btoa === 'function') {\n\t\t// Build a latin-1 string in chunks to avoid blowing the call stack on\n\t\t// large inputs (a single fromCharCode(...verylargearray) can exceed it).\n\t\tconst CHUNK = 0x8000;\n\t\tlet s = '';\n\t\tfor (let i = 0; i < bytes.length; i += CHUNK) {\n\t\t\ts += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + CHUNK)));\n\t\t}\n\t\treturn globalThis.btoa(s);\n\t}\n\tthrow new RhinoComputeError(\n\t\t'Base64 encoding not supported in this environment.',\n\t\tErrorCodes.INVALID_STATE,\n\t\t{ context: { environmentInfo: 'btoa or Buffer not available' } }\n\t);\n}\n\n/**\n * Convert base64 string to rhino object\n *\n * @internal Internal helper for decoding Rhino objects — not public API.\n *\n * Source: https://github.com/mcneel/compute.rhino3d.appserver/blob/92c95a3b1d076a4d4a5360214ffd27c46425ff03/src/examples/convert/scriptjs\n * @param rhino is the rhino module form rhino3dm. Since not properly typed its not used here.\n * @param item\n * @returns\n */\nexport function base64ToRhinoObject(\n\trhino: any,\n\titem: {\n\t\ttype: string;\n\t\tdata: string;\n\t}\n) {\n\t//Make a type definition for this?\n\tlet decodata: null | object = null;\n\ttry {\n\t\tdecodata = JSON.parse(item.data);\n\t} catch (error) {\n\t\tdecodata = item;\n\t\tgetLogger().warn('Failed to parse JSON, returning original data:', error, item);\n\t}\n\tif (item.type === 'System.String') {\n\t\ttry {\n\t\t\treturn rhino.DracoCompression.decompressBase64String(decodata);\n\t\t} catch (error) {\n\t\t\tgetLogger().error('Failed to decompress Draco base64 string:', error);\n\t\t}\n\t} else if (\n\t\ttypeof decodata === 'object' &&\n\t\tObject.prototype.hasOwnProperty.call(decodata, 'opennurbs')\n\t) {\n\t\treturn rhino.CommonObject.decode(decodata);\n\t} else if (typeof decodata === 'object') {\n\t\ttry {\n\t\t\treturn rhino.CommonObject.decode(decodata);\n\t\t} catch (error) {\n\t\t\tgetLogger().error('Failed to decode Rhino object:', error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eStringToBase64","str","isBase64","str","decodeBase64ToBinary","base64File","buf","binary","bytes","i","RhinoComputeError","ErrorCodes","base64ByteArray","s"]}
|
package/dist/chunk-RBNF6MNH.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var T=Object.defineProperty;var M=(t,e,r)=>e in t?T(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var z=(t,e)=>{for(var r in e)T(t,r,{get:e[r],enumerable:!0})};var f=(t,e,r)=>M(t,typeof e!="symbol"?e+"":e,r);var u={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED"},d= exports.d =class t extends Error{constructor(r,n="UNKNOWN_ERROR",o){super(r);f(this,"code");f(this,"statusCode");f(this,"context");f(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=_optionalChain([o, 'optionalAccess', _2 => _2.statusCode]),this.context=_optionalChain([o, 'optionalAccess', _3 => _3.context]),this.originalError=_optionalChain([o, 'optionalAccess', _4 => _4.originalError]),_optionalChain([o, 'optionalAccess', _5 => _5.originalError])&&(this.cause=o.originalError)}static missingValues(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,u.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,u.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};var b=class{debug(){}info(){}warn(){}error(){}},w=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},N=new b;function p(){return N}function C(t){N=t===null?new b:t}function k(){C(new w)}var E={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},A=new Set([502,503,504]);function D(t){return t?{attempts:_nullishCoalesce(t.attempts, () => (E.attempts)),baseDelayMs:_nullishCoalesce(t.baseDelayMs, () => (E.baseDelayMs)),maxDelayMs:_nullishCoalesce(t.maxDelayMs, () => (E.maxDelayMs)),retryOn429:_nullishCoalesce(t.retryOn429, () => (E.retryOn429))}:E}function x(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e)&&e>=0)return e*1e3;let r=Date.parse(t);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return null}function v(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function L(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",l)]),r()},t),l=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",l,{once:!0})])})}function U(t,e,r,n,o,l){let{status:c,statusText:s}=t,a={};t.headers.forEach(($,_)=>{a[_]=$});let i=l.trim(),R=i?` \u2014 ${i.slice(0,200)}${i.length>200?"\u2026":""}`:"",h={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:l||void 0,responseHeaders:a},g={401:{message:`HTTP ${c}: ${s}${R}`,code:u.AUTH_ERROR},403:{message:`HTTP ${c}: ${s}${R}`,code:u.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:u.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:u.VALIDATION_ERROR},429:{message:`Rate limit exceeded${R}`,code:u.NETWORK_ERROR},500:{message:`Server error: ${s}${R}`,code:u.COMPUTATION_ERROR},502:{message:`Service unavailable: ${s}${R}`,code:u.NETWORK_ERROR},503:{message:`Service unavailable: ${s}${R}`,code:u.NETWORK_ERROR},504:{message:`Service unavailable: ${s}${R}`,code:u.NETWORK_ERROR}}[c]||{message:`HTTP ${c}: ${s}${R}`,code:u.UNKNOWN_ERROR};throw new d(g.message,g.code,{statusCode:c,context:h})}function q(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function K(t){try{let e=new URL(t).host;return/^(localhost|127\.0\.0\.1|::1)(:\d+)?$/i.test(e)}catch (e2){return/(localhost|127\.0\.0\.1)/i.test(t)}}function P(t,e){let r={"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!K(e.serverUrl)&&p().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key is configured. Requests may fail or be rate-limited.`),r}function F(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function m(t,e){e&&p().debug(t)}function H(t,e){let r=[],n=()=>{};if(t&&r.push(t),e&&e>0)if(typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function")r.push(AbortSignal.timeout(e));else{let s=new AbortController,a=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(a),r.push(s.signal)}if(r.length===0)return{signal:void 0,cleanup:n};if(r.length===1)return{signal:r[0],cleanup:n};if(typeof AbortSignal<"u"&&typeof AbortSignal.any=="function")return{signal:AbortSignal.any(r),cleanup:n};let o=new AbortController,l=()=>o.abort();for(let s of r){if(s.aborted){o.abort();break}s.addEventListener("abort",l,{once:!0})}let c=n;return n=()=>{c();for(let s of r)s.removeEventListener("abort",l)},{signal:o.signal,cleanup:n}}async function W(t,e,r,n,o,l,c){let s=Math.round(performance.now()-l);if(!t.ok){let a=await t.text();if(c&&(m(`\u274C Request [${r}] failed with HTTP ${t.status} in ${s}ms`,!0),m(` URL: ${e}`,!0),m(` Status: ${t.status} ${t.statusText}`,!0),a&&m(` Response body: ${a.substring(0,500)}${a.length>500?"...":""}`,!0)),t.status===500)try{let i=JSON.parse(a);if(_optionalChain([i, 'optionalAccess', _11 => _11.values])&&(i.errors||i.warnings))return c&&(m(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${s}ms`,!0),_optionalChain([i, 'access', _12 => _12.errors, 'optionalAccess', _13 => _13.length])>0&&m(` Errors: ${JSON.stringify(i.errors,null,2)}`,!0),_optionalChain([i, 'access', _14 => _14.warnings, 'optionalAccess', _15 => _15.length])>0&&m(` Warnings: ${JSON.stringify(i.warnings,null,2)}`,!0)),i;_optionalChain([i, 'optionalAccess', _16 => _16.Message])?a=`${i.ExceptionType?i.ExceptionType+": ":""}${i.Message}
|
|
2
|
-
${i.StackTrace||""}`:_optionalChain([i, 'optionalAccess', _17 => _17.error])&&(a=typeof i.error=="string"?i.error:JSON.stringify(i.error,null,2))}catch(i){c&&m(` Failed to parse error body as JSON: ${i}`,!0)}U(t,e,r,n,o,a)}m(`\u2705 Request [${r}] completed in ${s}ms`,c);try{return await t.json()}catch(a){throw new d("Failed to parse JSON response",u.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:a instanceof Error?a:new Error(String(a))})}}async function V(t,e,r,n){let{signal:o,cleanup:l}=H(t.config.signal,t.config.timeoutMs),c=performance.now();try{let s=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((A.has(s.status)||e.retryOn429&&s.status===429)&&r<n-1){let h=_nullishCoalesce(x(s.headers.get("Retry-After")), () => (v(r,e)));return await s.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:h,cause:new d(`HTTP ${s.status} ${s.statusText} (will retry)`,u.NETWORK_ERROR,{statusCode:s.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await W(s,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,c,t.config.debug)}}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")){if(_optionalChain([t, 'access', _18 => _18.config, 'access', _19 => _19.signal, 'optionalAccess', _20 => _20.aborted])===!0)return{ok:!1,retry:!1,cause:new d("Request aborted by caller",u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:s})};let i=new d(`Request timed out after ${t.config.timeoutMs}ms`,u.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize}});return r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:i}:{ok:!1,retry:!1,cause:i}}if(s instanceof TypeError){let a=new d(`Network error: ${s.message}`,u.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:s});return r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:a}:{ok:!1,retry:!1,cause:a}}if(s instanceof d){let a=s.statusCode;return a!==void 0&&(A.has(a)||e.retryOn429&&a===429)&&r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:s}:{ok:!1,retry:!1,cause:s}}return{ok:!1,retry:!1,cause:new d(s instanceof Error?s.message:String(s),u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:s instanceof Error?s:new Error(String(s))})}}finally{l()}}async function G(t,e,r){let n=F(),o=JSON.stringify(e),l=o.length,c=q(t,r.serverUrl),s=P(n,r),a=D(r.retry),i=a.attempts+1;if(r.debug){let y=(l/1024).toFixed(2),g=l>1e5?"\u26A0\uFE0F":"\u{1F680}";m(`${g} Starting compute request [${n}]: ${t} (${y}KB)`,!0)}let R={endpoint:t,body:o,requestSize:l,fullUrl:c,requestId:n,headers:s,config:r},h=null;for(let y=0;y<i;y++){let g=await V(R,a,y,i);if(g.ok)return g.value;if(!g.retry)throw g.cause;h=g.cause,r.debug&&m(`\u{1F501} Request [${n}] retrying after ${g.delayMs}ms (attempt ${y+2}/${i}): ${g.cause.message}`,!0);try{await L(g.delayMs,r.signal)}catch (e3){throw new d("Request aborted by caller",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:l},originalError:h})}}throw _nullishCoalesce(h, () => (new d("Unknown error after retries",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:l}})))}var O=class{constructor(e,r){f(this,"serverUrl");f(this,"apiKey");f(this,"disposed",!1);f(this,"activeMonitors",new Set);f(this,"activeTimeouts",new Set);if(!_optionalChain([e, 'optionalAccess', _21 => _21.trim, 'call', _22 => _22()]))throw new d("serverUrl is required",u.INVALID_CONFIG,{context:{serverUrl:e}});if(!e.match(/^https?:\/\//))throw new d(`Invalid serverUrl: "${e}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,u.INVALID_CONFIG,{context:{serverUrl:e}});try{new URL(e)}catch(n){throw new d(`Invalid serverUrl: "${e}". Must be a valid URL. Received error: ${n instanceof Error?n.message:String(n)}`,u.INVALID_CONFIG,{context:{serverUrl:e},originalError:n instanceof Error?n:void 0})}this.apiKey=r,this.serverUrl=e.replace(/\/+$/,"")}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}async isServerOnline(){this.ensureNotDisposed();let e=`${this.serverUrl}/healthcheck`,r={headers:this.buildHeaders(),method:"GET"};try{return(await fetch(e,r)).ok}catch(n){return p().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(){this.ensureNotDisposed();try{let e=await fetch(`${this.serverUrl}/activechildren`,{headers:this.buildHeaders()});if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch active children:",e.status),null;let r=await e.text(),n=parseInt(r.trim(),10);return isNaN(n)?(p().warn("[ComputeServerStats] Invalid active children response:",r),null):n}catch(e){return p().warn("[ComputeServerStats] Error fetching active children:",e),null}}async getVersion(){this.ensureNotDisposed();try{let e=await fetch(`${this.serverUrl}/version`,{headers:this.buildHeaders()});if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e4){return{rhino:r,compute:"",git_sha:null}}}catch(e){return p().warn("[ComputeServerStats] Error fetching version:",e),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren()]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}monitor(e,r=5e3){this.ensureNotDisposed();let n=!0,o=null;p().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let l=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let s=await this.getServerStats();if(!n||this.disposed)return;try{e(s)}catch(a){p().error("[ComputeServerStats] Monitor callback threw:",a)}}catch(s){p().error("[ComputeServerStats] Failed to fetch stats during monitor:",s)}n&&!this.disposed&&(o=setTimeout(()=>{l()},r),this.activeTimeouts.add(o))}},c=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(c)};return this.activeMonitors.add(c),l(),c}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new d("ComputeServerStats has been disposed and cannot be used",u.INVALID_STATE,{context:{disposed:this.disposed}})}};function I(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s-_]+(.)?/g,o=t.trim();return o.charAt(0).toLowerCase()+o.slice(1).replace(n,(l,c)=>c?c.toUpperCase():"")}function S(t,e={}){return!t||typeof t!="object"?t:Array.isArray(t)?e.deep?t.map(r=>S(r,e)):t:Object.keys(t).reduce((r,n)=>{let o=I(n,{preserveSpaces:e.preserveSpaces}),l=t[n];return r[o]=e.deep?S(l,e):l,r},{})}exports.a = z; exports.b = f; exports.c = u; exports.d = d; exports.e = p; exports.f = C; exports.g = k; exports.h = G; exports.i = O; exports.j = I; exports.k = S;
|
|
3
|
-
//# sourceMappingURL=chunk-RBNF6MNH.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-RBNF6MNH.cjs","../src/core/errors.ts","../src/core/compute-fetch/compute-fetch.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,qrBAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC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AAOF,CAAAA,CACZ,IAAA,CAAK,UAAA,iBAAaC,CAAAA,6BAAS,YAAA,CAC3B,IAAA,CAAK,OAAA,iBAAUA,CAAAA,6BAAS,SAAA,CACxB,IAAA,CAAK,aAAA,iBAAgBA,CAAAA,6BAAS,eAAA,iBAC1BA,CAAAA,6BAAS,eAAA,EAAA,CACX,IAAA,CAA6B,KAAA,CAAQA,CAAAA,CAAQ,aAAA,CAEhD,CASA,OAAO,aAAA,CACNE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAO,IAAIP,CAAAA,CACV,CAAA,OAAA,EAAUK,CAAS,CAAA,uBAAA,EAA0BC,CAAAA,CAAe,CAAA,WAAA,EAAcA,CAAY,CAAA,CAAA,CAAA,CAAM,EAAE,CAAA,CAAA;AC+VlB","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-RBNF6MNH.cjs","sourcesContent":[null,"/**\n * Error types and codes for `@selvajs/compute`.\n */\n\nexport const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: string;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: string = 'UNKNOWN_ERROR',\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Static Validation Error Helpers\n\t// ============================================================================\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { ComputeConfig, RetryPolicy } from '../types';\nimport type {\n\tGrasshopperComputeConfig,\n\tGrasshopperComputeResponse,\n\tIoResponseSchema\n} from '@/features/grasshopper/types';\n\n/**\n * Valid endpoints for Rhino Compute (improved response type handling).\n */\nexport type Endpoint = 'grasshopper' | 'io' | string;\n\nexport type EndpointResponseMap = {\n\tgrasshopper: GrasshopperComputeResponse;\n\tio: IoResponseSchema;\n};\n\nexport type ComputeResponseFor<E extends string> = E extends keyof EndpointResponseMap\n\t? EndpointResponseMap[E]\n\t: unknown;\n\n// ============================================================================\n// Retry Policy\n// ============================================================================\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed\n\t\t? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}`\n\t\t: '';\n\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: errorBody || undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: string }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: { message: `Service unavailable: ${statusText}${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t503: { message: `Service unavailable: ${statusText}${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t504: { message: `Service unavailable: ${statusText}${bodyHint}`, code: ErrorCodes.NETWORK_ERROR }\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\tthrow new RhinoComputeError(error.message, error.code, { statusCode: status, context });\n}\n\n// ============================================================================\n// Request Helpers\n// ============================================================================\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\tconst host = new URL(serverUrl).host;\n\t\treturn /^(localhost|127\\.0\\.0\\.1|::1)(:\\d+)?$/i.test(host);\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1)/i.test(serverUrl);\n\t}\n}\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (!config.apiKey && !isLocalhost(config.serverUrl)) {\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key is configured. Requests may fail or be rate-limited.`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst signals: AbortSignal[] = [];\n\tlet cleanup = () => {};\n\n\tif (callerSignal) signals.push(callerSignal);\n\n\tif (timeoutMs && timeoutMs > 0) {\n\t\tif (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {\n\t\t\tsignals.push(AbortSignal.timeout(timeoutMs));\n\t\t} else {\n\t\t\t// Fallback for runtimes without AbortSignal.timeout\n\t\t\tconst ctrl = new AbortController();\n\t\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\t\tcleanup = () => clearTimeout(id);\n\t\t\tsignals.push(ctrl.signal);\n\t\t}\n\t}\n\n\tif (signals.length === 0) return { signal: undefined, cleanup };\n\tif (signals.length === 1) return { signal: signals[0], cleanup };\n\n\tif (typeof AbortSignal !== 'undefined' && typeof (AbortSignal as any).any === 'function') {\n\t\treturn { signal: (AbortSignal as any).any(signals) as AbortSignal, cleanup };\n\t}\n\n\t// Manual composition fallback\n\tconst ctrl = new AbortController();\n\tconst onAbort = () => ctrl.abort();\n\tfor (const s of signals) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort();\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\tconst prevCleanup = cleanup;\n\tcleanup = () => {\n\t\tprevCleanup();\n\t\tfor (const s of signals) s.removeEventListener('abort', onAbort);\n\t};\n\treturn { signal: ctrl.signal, cleanup };\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse\n\t\tlet errorBody = await response.text();\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// If it's a raw exception from the server (like ArgumentException), include it in the error message\n\t\t\t\tif (parsed?.Message) {\n\t\t\t\t\terrorBody = `${parsed.ExceptionType ? parsed.ExceptionType + ': ' : ''}${parsed.Message}\\n${parsed.StackTrace || ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(response, fullUrl, requestId, requestSize, serverUrl, errorBody);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\ttry {\n\t\treturn await response.json();\n\t} catch (error) {\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Single attempt\n// ============================================================================\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig | GrasshopperComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\tconst delayMs = retryAfterMs ?? backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t},\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Timeout — retryable up to attempts limit\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable\n\t\tif (error instanceof TypeError) {\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Network error: ${error.message}`,\n\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t},\n\t\t\t\t\toriginalError: error\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\tconst retryable =\n\t\t\t\tstatus !== undefined &&\n\t\t\t\t(RETRYABLE_STATUS.has(status) || (retryPolicy.retryOn429 && status === 429));\n\t\t\tif (retryable && attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: error };\n\t\t}\n\n\t\t// Unknown — wrap and don't retry\n\t\treturn {\n\t\t\tok: false,\n\t\t\tretry: false,\n\t\t\tcause: new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.UNKNOWN_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: { endpoint: ctx.endpoint, requestId: ctx.requestId },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t)\n\t\t};\n\t} finally {\n\t\tcleanup();\n\t}\n}\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Generic Rhino Compute fetch function.\n * Sends a POST request to any Compute endpoint with pre-prepared arguments.\n *\n * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs.\n *\n * @typeParam E - The endpoint name (e.g., 'grasshopper', 'io'). Determines the response type for better type safety.\n * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh').\n * @param args - Pre-prepared arguments for the request body.\n * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal).\n * @returns The parsed JSON response from the server, typed according to the endpoint.\n *\n * @example\n * // Basic usage for the Grasshopper endpoint:\n * const response = await fetchRhinoCompute(\n * 'grasshopper',\n * { ... },\n * {\n * serverUrl: 'https://my-server.com',\n * debug: true,\n * timeoutMs: 30_000,\n * retry: { attempts: 2 },\n * signal: controller.signal,\n * }\n * );\n */\nexport async function fetchRhinoCompute<E extends Endpoint>(\n\tendpoint: E,\n\targs: Record<string, any>,\n\tconfig: ComputeConfig | GrasshopperComputeConfig\n): Promise<ComputeResponseFor<E>> {\n\tconst requestId = generateRequestId();\n\tconst body = JSON.stringify(args);\n\tconst requestSize = body.length;\n\tconst fullUrl = buildUrl(endpoint, config.serverUrl);\n\tconst headers = buildHeaders(requestId, config);\n\tconst retryPolicy = resolveRetryPolicy(config.retry);\n\tconst totalAttempts = retryPolicy.attempts + 1;\n\n\tif (config.debug) {\n\t\tconst sizeKb = (requestSize / 1024).toFixed(2);\n\t\tconst emoji = requestSize > 100000 ? '⚠️' : '🚀';\n\t\tlog(`${emoji} Starting compute request [${requestId}]: ${endpoint} (${sizeKb}KB)`, true);\n\t}\n\n\tconst ctx: AttemptContext = {\n\t\tendpoint,\n\t\tbody,\n\t\trequestSize,\n\t\tfullUrl,\n\t\trequestId,\n\t\theaders,\n\t\tconfig\n\t};\n\n\tlet lastError: RhinoComputeError | null = null;\n\n\tfor (let attempt = 0; attempt < totalAttempts; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as ComputeResponseFor<E>;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tlastError = result.cause;\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: lastError\n\t\t\t});\n\t\t}\n\t}\n\n\t// Exhausted retries — throw the last seen error\n\tthrow (\n\t\tlastError ??\n\t\tnew RhinoComputeError('Unknown error after retries', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\tcontext: { endpoint, requestId, requestSize }\n\t\t})\n\t);\n}\n"]}
|
package/dist/chunk-SVEXPGHW.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkZRQRYG6Fcjs = require('./chunk-ZRQRYG6F.cjs');var _chunkRBNF6MNHcjs = require('./chunk-RBNF6MNH.cjs');var _three = require('three'); var s = _interopRequireWildcard(_three); var w = _interopRequireWildcard(_three); var b = _interopRequireWildcard(_three); var M = _interopRequireWildcard(_three);var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var V=new s.Vector3(0,0,1),P=(e,r,n,t)=>{switch(e){case"mm":return r;case"cm":return n;default:return t}},Ze= exports.a =function(e,r){let n=oe(r||{}),t=ae(n),o=de(n,e),a=me(e,n),i=he(o,e,n);le(t,n),ce(t,n),_optionalChain([n, 'access', _2 => _2.floor, 'optionalAccess', _3 => _3.enabled])&&ue(t,n);let c=n.events.enableEventHandlers!==!1?fe(e,t,o,i,n):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},l=e.parentElement,h=()=>l?{width:l.clientWidth,height:l.clientHeight}:{width:window.innerWidth,height:window.innerHeight},{animate:m,dispose:u}=se(a,t,o,i,h,n.events.onFrame);m();let E=_optionalChain([n, 'access', _4 => _4.environment, 'optionalAccess', _5 => _5.sceneUp])||V;return t.up.set(E.x,E.y,E.z),{scene:t,camera:o,controls:i,renderer:a,dispose:()=>{u(),c.dispose(),i.dispose(),a.dispose(),t.traverse(d=>{d instanceof s.Mesh&&(_optionalChain([d, 'access', _6 => _6.geometry, 'optionalAccess', _7 => _7.dispose, 'call', _8 => _8()]),Array.isArray(d.material)?d.material.forEach(H=>H.dispose()):_optionalChain([d, 'access', _9 => _9.material, 'optionalAccess', _10 => _10.dispose, 'call', _11 => _11()]))})},fitToView:c.fitToView,clearSelection:c.clearSelection}};function oe(e){let r=e.sceneScale||"m",t={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:_optionalChain([e, 'access', _12 => _12.camera, 'optionalAccess', _13 => _13.position])||new s.Vector3(-t.cameraDistance,t.cameraDistance,t.cameraDistance),fov:_optionalChain([e, 'access', _14 => _14.camera, 'optionalAccess', _15 => _15.fov])||20,near:_optionalChain([e, 'access', _16 => _16.camera, 'optionalAccess', _17 => _17.near])||t.near,far:_optionalChain([e, 'access', _18 => _18.camera, 'optionalAccess', _19 => _19.far])||t.far,target:_optionalChain([e, 'access', _20 => _20.camera, 'optionalAccess', _21 => _21.target])||new s.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _22 => _22.lighting, 'optionalAccess', _23 => _23.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _24 => _24.lighting, 'optionalAccess', _25 => _25.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _26 => _26.lighting, 'optionalAccess', _27 => _27.sunlightPosition])||new s.Vector3(t.lightDistance,t.lightHeight,t.lightDistance),ambientLightColor:_optionalChain([e, 'access', _28 => _28.lighting, 'optionalAccess', _29 => _29.ambientLightColor])||new s.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _30 => _30.lighting, 'optionalAccess', _31 => _31.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _32 => _32.lighting, 'optionalAccess', _33 => _33.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _34 => _34.environment, 'optionalAccess', _35 => _35.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _36 => _36.environment, 'optionalAccess', _37 => _37.backgroundColor])||new s.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _38 => _38.environment, 'optionalAccess', _39 => _39.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _40 => _40.environment, 'optionalAccess', _41 => _41.sceneUp])||V,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _42 => _42.environment, 'optionalAccess', _43 => _43.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _44 => _44.floor, 'optionalAccess', _45 => _45.enabled]), () => (!1)),size:_optionalChain([e, 'access', _46 => _46.floor, 'optionalAccess', _47 => _47.size])||t.floorSize,color:_optionalChain([e, 'access', _48 => _48.floor, 'optionalAccess', _49 => _49.color])||new s.Color(8421504),roughness:_optionalChain([e, 'access', _50 => _50.floor, 'optionalAccess', _51 => _51.roughness])||.7,metalness:_optionalChain([e, 'access', _52 => _52.floor, 'optionalAccess', _53 => _53.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _54 => _54.floor, 'optionalAccess', _55 => _55.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _56 => _56.render, 'optionalAccess', _57 => _57.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _58 => _58.render, 'optionalAccess', _59 => _59.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.render, 'optionalAccess', _61 => _61.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _62 => _62.render, 'optionalAccess', _63 => _63.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _64 => _64.render, 'optionalAccess', _65 => _65.toneMapping])||s.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _66 => _66.render, 'optionalAccess', _67 => _67.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _68 => _68.render, 'optionalAccess', _69 => _69.preserveDrawingBuffer]), () => (!1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.controls, 'optionalAccess', _71 => _71.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _72 => _72.controls, 'optionalAccess', _73 => _73.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.controls, 'optionalAccess', _75 => _75.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _76 => _76.controls, 'optionalAccess', _77 => _77.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _78 => _78.controls, 'optionalAccess', _79 => _79.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _80 => _80.controls, 'optionalAccess', _81 => _81.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _82 => _82.controls, 'optionalAccess', _83 => _83.minDistance])||t.minDistance,maxDistance:_optionalChain([e, 'access', _84 => _84.controls, 'optionalAccess', _85 => _85.maxDistance])||1/0},events:{onBackgroundClicked:_optionalChain([e, 'access', _86 => _86.events, 'optionalAccess', _87 => _87.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _88 => _88.events, 'optionalAccess', _89 => _89.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _90 => _90.events, 'optionalAccess', _91 => _91.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _92 => _92.events, 'optionalAccess', _93 => _93.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _94 => _94.events, 'optionalAccess', _95 => _95.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.events, 'optionalAccess', _97 => _97.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.events, 'optionalAccess', _99 => _99.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.events, 'optionalAccess', _101 => _101.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.events, 'optionalAccess', _103 => _103.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _104 => _104.events, 'optionalAccess', _105 => _105.onReady]),onFrame:_optionalChain([e, 'access', _106 => _106.events, 'optionalAccess', _107 => _107.onFrame])}}}function ae(e){let r=new s.Scene,n=typeof e.environment.backgroundColor=="string"?new s.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=n||null,r}function ie(e,r,n,t,o=200){let a=e.position.clone(),i=r.target.clone(),c=performance.now(),l=m=>1-Math.pow(1-m,3),h=()=>{let m=performance.now()-c,u=l(Math.min(m/o,1));e.position.lerpVectors(a,n,u),r.target.lerpVectors(i,t,u),r.update(),u<1&&requestAnimationFrame(h)};requestAnimationFrame(h)}function se(e,r,n,t,o,a){let i=null,c=performance.now(),l=()=>{let{width:u,height:E}=o();if(u===0||E===0)return;let g=Math.min(window.devicePixelRatio,2),d=Math.round(u*g),H=Math.round(E*g);(e.domElement.width!==d||e.domElement.height!==H)&&(e.setPixelRatio(g),e.setSize(u,E,!1),n.aspect=u/E,n.updateProjectionMatrix())},h=function(){i=requestAnimationFrame(h);let u=performance.now(),E=(u-c)/1e3;c=u,l(),(t.enableDamping||t.autoRotate)&&t.update(),_optionalChain([a, 'optionalCall', _108 => _108(E)]),e.render(r,n)};return{animate:h,dispose:()=>{i!==null&&(cancelAnimationFrame(i),i=null)}}}function le(e,r){r.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(n){n.mapping=s.EquirectangularReflectionMapping,e.environment=n,r.environment.showEnvironment&&(e.background=n),_optionalChain([r, 'access', _109 => _109.events, 'access', _110 => _110.onReady, 'optionalCall', _111 => _111()])},void 0,function(n){_chunkRBNF6MNHcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",n),_optionalChain([r, 'access', _112 => _112.events, 'access', _113 => _113.onReady, 'optionalCall', _114 => _114()])}):_optionalChain([r, 'access', _115 => _115.events, 'access', _116 => _116.onReady, 'optionalCall', _117 => _117()])}function ce(e,r){let n=new s.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(n),r.lighting.enableSunlight){let t=new s.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&t.position.set(o.x,o.y,o.z),r.render.enableShadows){t.castShadow=!0;let a=P(r.sceneScale,.1,10,100);t.shadow.camera.left=-a,t.shadow.camera.right=a,t.shadow.camera.top=a,t.shadow.camera.bottom=-a;let i=P(r.sceneScale,.001,.1,.5),c=P(r.sceneScale,1,100,500);t.shadow.camera.near=i,t.shadow.camera.far=c,t.shadow.mapSize.width=r.render.shadowMapSize||2048,t.shadow.mapSize.height=r.render.shadowMapSize||2048,t.shadow.bias=-1e-4,t.shadow.normalBias=.02}e.add(t)}}function ue(e,r){let n=r.floor.size,t=new s.PlaneGeometry(n,n),o=typeof r.floor.color=="string"?new s.Color(r.floor.color):r.floor.color,a=new s.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:s.DoubleSide}),i=new s.Mesh(t,a);i.userData.id="floor",i.name="floor",i.rotation.x=-Math.PI/2,i.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function de(e,r){let n=r.parentElement,t=n?n.clientWidth:window.innerWidth,o=n?n.clientHeight:window.innerHeight,a=new s.PerspectiveCamera(e.camera.fov,t/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function me(e,r){let n=new s.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),t=e.parentElement,o=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight;return t&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),n.setSize(o,a,!1),n.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(n.shadowMap.enabled=!0,n.shadowMap.type=s.VSMShadowMap),n.toneMapping=r.render.toneMapping,n.toneMappingExposure=r.render.toneMappingExposure||1,n.outputColorSpace=s.SRGBColorSpace,n.sortObjects=!0,n}function fe(e,r,n,t,o){let a=new Set,i=new Map,c=new s.Raycaster,l=new s.Vector2,h=new s.Vector2,m=f=>{let p=f;for(;p;){if(!p.visible)return!1;p=p.parent}return!0},u=()=>{let f=new s.Box3;if(r.traverse(A=>{A.visible&&A.userData.id!=="floor"&&A instanceof s.Mesh&&f.expandByObject(A)}),f.isEmpty()){_chunkRBNF6MNHcjs.e.call(void 0, ).warn("No objects to fit to view");return}let p=f.getCenter(new s.Vector3),T=f.getSize(new s.Vector3),v=Math.max(T.x,T.y,T.z),R=n.fov*(Math.PI/180),S=v/(2*Math.tan(R/2));S*=1.5;let O=n.position.clone().sub(t.target).normalize();n.position.copy(p.clone().add(O.multiplyScalar(S))),t.target.copy(p),t.update()},E=typeof o.events.selectionColor=="string"?new s.Color(o.events.selectionColor):o.events.selectionColor instanceof s.Color?o.events.selectionColor:new s.Color("#ff0000"),g=()=>{a.forEach(f=>{f instanceof s.Mesh&&i.has(f)&&(f.material=i.get(f),i.delete(f))}),a.clear()},d=f=>{h.set(f.clientX,f.clientY)},H=f=>{let p=new s.Vector2(f.clientX,f.clientY);if(h.distanceTo(p)>5)return;let T=e.getBoundingClientRect();l.x=(f.clientX-T.left)/T.width*2-1,l.y=-((f.clientY-T.top)/T.height)*2+1,c.setFromCamera(l,n);let v=c.intersectObjects(r.children,!0).filter(R=>m(R.object));if(v.length>0){let R=v[0].object;if(!a.has(R)){if(g(),a.add(R),R instanceof s.Mesh&&R.material instanceof s.Material){i.set(R,R.material);let S=R.material.clone();S.emissive=E.clone(),R.material=S}_optionalChain([o, 'access', _118 => _118.events, 'optionalAccess', _119 => _119.onObjectSelected, 'optionalCall', _120 => _120(R)]),R instanceof s.Mesh&&Object.keys(R.userData).length>0&&_optionalChain([o, 'access', _121 => _121.events, 'optionalAccess', _122 => _122.onMeshMetadataClicked, 'optionalCall', _123 => _123(R.userData)])}}else g(),_optionalChain([o, 'access', _124 => _124.events, 'optionalAccess', _125 => _125.onBackgroundClicked, 'optionalCall', _126 => _126({x:l.x,y:l.y})])},L=f=>{let p=e.getBoundingClientRect();l.x=(f.clientX-p.left)/p.width*2-1,l.y=-((f.clientY-p.top)/p.height)*2+1,c.setFromCamera(l,n);let T=c.intersectObjects(r.children,!0).filter(ee=>m(ee.object));if(T.length===0)return;let v=T[0].object;if(_optionalChain([o, 'access', _127 => _127.events, 'optionalAccess', _128 => _128.onMeshDoubleClicked, 'optionalCall', _129 => _129(v)]),!_optionalChain([o, 'access', _130 => _130.events, 'optionalAccess', _131 => _131.enableDoubleClickZoom]))return;let R=new s.Box3().setFromObject(v);if(R.isEmpty())return;let S=R.getCenter(new s.Vector3),O=R.getSize(new s.Vector3),A=Math.max(O.x,O.y,O.z),K=n.fov*(Math.PI/180),X=A/(2*Math.tan(K/2))*1.5,J=n.position.clone().sub(t.target).normalize(),Q=S.clone().add(J.multiplyScalar(X));ie(n,t,Q,S)},x=f=>{if(_optionalChain([o, 'access', _132 => _132.events, 'optionalAccess', _133 => _133.enableKeyboardControls]))switch(f.key.toLowerCase()){case"f":f.preventDefault(),u();break;case"escape":f.preventDefault(),g();break;case" ":f.preventDefault(),u();break}};return _optionalChain([o, 'access', _134 => _134.events, 'optionalAccess', _135 => _135.enableClickToFocus])&&(e.addEventListener("mousedown",d),e.addEventListener("click",H),e.addEventListener("dblclick",L)),_optionalChain([o, 'access', _136 => _136.events, 'optionalAccess', _137 => _137.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",d),e.removeEventListener("click",H),e.removeEventListener("dblclick",L),e.removeEventListener("keydown",x),g()},fitToView:u,clearSelection:g}}function he(e,r,n){let t=new (0, _OrbitControlsjs.OrbitControls)(e,r),o=n.camera.target;return o&&t.target.set(o.x,o.y,o.z),t.enableDamping=n.controls.enableDamping||!1,t.dampingFactor=n.controls.dampingFactor||.05,t.autoRotate=n.controls.autoRotate||!1,t.autoRotateSpeed=n.controls.autoRotateSpeed||.5,t.enableZoom=_nullishCoalesce(n.controls.enableZoom, () => (!0)),t.enablePan=_nullishCoalesce(n.controls.enablePan, () => (!0)),t.minDistance=n.controls.minDistance||.001,t.maxDistance=n.controls.maxDistance||1/0,t.screenSpacePanning=!1,t.maxPolarAngle=Math.PI,t.update(),t}var B={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function Xe(e,r,n,t,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let a=z(r),i=a.getCenter(new w.Vector3),c=a.getSize(new w.Vector3),l=Math.max(c.x,c.y,c.z);if(l/Math.min(c.x||1,c.y||1,c.z||1)>B.SCALE_RATIO_THRESHOLD||l>B.HUGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.TINY,n.far=l*B.FAR_PLANE_FACTOR.HUGE):l>B.LARGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.SMALL,n.far=l*B.FAR_PLANE_FACTOR.LARGE):(n.near=Math.max(.01,l*B.NEAR_PLANE_FACTOR.NORMAL),n.far=Math.max(2e3,l*B.FAR_PLANE_FACTOR.NORMAL)),n.updateProjectionMatrix(),o)t.minDistance=n.near*2,t.maxDistance=n.far*.9;else{let m=l*B.INITIAL_DISTANCE_MULTIPLIER;n.position.set(i.x+m*.8,i.y+m,i.z+m*1.2),t.target.copy(i),t.minDistance=n.near*2,t.maxDistance=n.far*.9,t.update()}}function N(e){if(!e||typeof e!="string")return _chunkRBNF6MNHcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let n=r.startsWith("#")?r:`#${r}`;return new w.Color(n)}catch (e2){return _chunkRBNF6MNHcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let n=r.split(",").map(t=>parseInt(t.trim(),10));if(n.length===3&&n.every(t=>!isNaN(t)&&t>=0&&t<=255))return new w.Color(n[0]/255,n[1]/255,n[2]/255)}try{return new w.Color(r.toLowerCase())}catch (e3){return _chunkRBNF6MNHcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function G(e,r){e.forEach(n=>{n.position.y-=r})}function z(e){let r=new w.Box3;return e.length===0||e.forEach(n=>{n.updateMatrixWorld(!0);let t=new w.Box3().setFromObject(n);r.union(t)}),r}function Ee(e){[...e.children].forEach(n=>{n.userData.id!=="floor"&&(n.traverse(t=>{if(!(t instanceof w.Mesh))return;_optionalChain([t, 'access', _138 => _138.geometry, 'optionalAccess', _139 => _139.dispose, 'call', _140 => _140()]),(Array.isArray(t.material)?t.material:[t.material]).forEach(a=>{for(let i of Object.values(a))i instanceof w.Texture&&i.dispose();a.dispose()})}),n.removeFromParent())})}var Me={};_chunkRBNF6MNHcjs.a.call(void 0, Me,{CONCRETE_MATERIAL:()=>ye,EMISSIVE_MATERIAL:()=>pe,GLASS_MATERIAL:()=>Re,METAL_MATERIAL:()=>ge,PLASTIC_MATERIAL:()=>be,RUBBER_MATERIAL:()=>Te,WOOD_MATERIAL:()=>we});var pe=new b.MeshPhysicalMaterial({color:0,emissive:new b.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ge=new b.MeshPhysicalMaterial({color:new b.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ye=new b.MeshPhysicalMaterial({color:new b.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),be=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Re=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new b.MeshPhysicalMaterial({color:new b.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new b.MeshPhysicalMaterial({color:new b.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var $=1096174675,W= exports.h =1,k= exports.i =1,Y=12,j=56;function U(e){let r=He(e),n=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Y)throw I("Blob too small to contain SLVA header.",{expectedBytes:Y,availableBytes:r.byteLength});let t=0,o=n.getUint32(t,!0);if(t+=4,o!==$)throw I(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${$.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=n.getUint32(t,!0);if(t+=4,a!==W)throw I(`Unsupported SLVA version: ${a}`,{expectedVersion:W,actualVersion:a});let i=n.getUint32(t,!0);if(t+=4,t+i>r.byteLength)throw I("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-t,offset:t});let c=r.subarray(t,t+i);t+=i;let l;try{l=JSON.parse(xe(c))}catch(A){throw I(`Failed to parse metadata JSON: ${A instanceof Error?A.message:String(A)}`,{metadataLen:i})}if(t+j>r.byteLength)throw I("Insufficient data to read geometry header.",{expectedBytes:j,availableBytes:r.byteLength-t,offset:t});let h=n.getUint32(t,!0);t+=4;let m=n.getFloat64(t,!0);t+=8;let u=n.getFloat64(t,!0);t+=8;let E=n.getFloat64(t,!0);t+=8;let g=n.getFloat64(t,!0);t+=8;let d=n.getFloat64(t,!0);t+=8;let H=n.getFloat64(t,!0);t+=8;let L=n.getUint32(t,!0);t+=4;let x=(h&k)!==0,C=L*3,p=C*(x?4:2);if(t+p>r.byteLength)throw I("Insufficient data to read vertices.",{expectedBytes:p,availableBytes:r.byteLength-t,offset:t,useFloat32:x,vertexCount:L});let T=r.byteOffset+t,v=x?ve(r.buffer,T,C):Ce(r.buffer,T,C);if(t+=p,t+4>r.byteLength)throw I("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-t,offset:t});let R=n.getUint32(t,!0);t+=4;let S=R*4;if(t+S>r.byteLength)throw I("Insufficient data to read indices.",{expectedBytes:S,availableBytes:r.byteLength-t,offset:t,indexCount:R});let O=Se(r.buffer,r.byteOffset+t,R);return{metadata:l,flags:h,vertices:v,indices:O,origin:[m,u,E],scale:[g,d,H]}}function He(e){return typeof e=="string"?_chunkZRQRYG6Fcjs.c.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function xe(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new (0, _chunkRBNF6MNHcjs.d)("No UTF-8 decoder available in this environment.",_chunkRBNF6MNHcjs.c.INVALID_STATE)}function Ce(e,r,n){if(n===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,n);let t=new Uint8Array(n*2);return t.set(new Uint8Array(e,r,n*2)),new Int16Array(t.buffer)}function ve(e,r,n){if(n===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Float32Array(t.buffer)}function Se(e,r,n){if(n===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Uint32Array(t.buffer)}function I(e,r){return new (0, _chunkRBNF6MNHcjs.d)(e,_chunkRBNF6MNHcjs.c.VALIDATION_ERROR,{context:r})}async function Z(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),a=o?performance.now():0,i=0;try{let c=performance.now(),l=JSON.parse(e);return i=performance.now()-c,await Ae(l,{mergeByMaterial:n,applyTransforms:t,debug:o,parseTime:i,perfStart:a})}catch(c){return _chunkRBNF6MNHcjs.e.call(void 0, ).error("Error parsing mesh batch:",c),[]}}async function Ae(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1,parseTime:i=0,perfStart:c=a?performance.now():0}=_nullishCoalesce(r, () => ({}));try{let l=performance.now(),h=U(e.compressedData),m=performance.now()-l,u=a?Fe(e.compressedData):0;return q(h,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:m,perfStart:c,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(l){return _chunkRBNF6MNHcjs.e.call(void 0, ).error("Error parsing mesh batch object:",l),[]}}async function at(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1}=_nullishCoalesce(r, () => ({})),i=a?performance.now():0;try{let c=performance.now(),l=U(e),h=performance.now()-c,m=(e instanceof Uint8Array,e.byteLength);return q(l,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:0,decodeTime:h,perfStart:i,blobBytes:m})}catch(c){return _chunkRBNF6MNHcjs.e.call(void 0, ).error("Error parsing mesh batch blob:",c),[]}}function q(e,r){let{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:c,perfStart:l,blobBytes:h,fallback:m}=r,u=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([m, 'optionalAccess', _141 => _141.materials]))), () => ([])),E=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([m, 'optionalAccess', _142 => _142.groups]))), () => ([])),g=_nullishCoalesce(e.metadata.sourceComponentId, () => (_optionalChain([m, 'optionalAccess', _143 => _143.sourceComponentId]))),d=(e.flags&k)!==0,H=d?Le(e.vertices,t):Be(e.vertices,e.origin,e.scale,t);if(a){let p=e.vertices.byteLength+e.indices.byteLength;_chunkRBNF6MNHcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Materials: ${u.length} | Groups: ${E.length}`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Format: ${d?"float32":"int16 quantized"}`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Blob: ${(h/1024/1024).toFixed(2)} MB | Geometry on wire: ${(p/1024/1024).toFixed(2)} MB`)}let L=performance.now(),x=u.map(Ie),C=[];for(let p of E)if(n&&p.meshes.length>1){let T=Oe(p,H,e.indices,x);T.userData.sourceComponentId=_nullishCoalesce(g, () => (null)),C.push(T)}else{let T=De(p,H,e.indices,x);for(let v of T)v.userData.sourceComponentId=_nullishCoalesce(g, () => (null));C.push(...T)}if(o!==1)for(let p of C)p.scale.set(o,o,o);let f=performance.now()-L;if(a){let p=performance.now()-l;_chunkRBNF6MNHcjs.e.call(void 0, ).debug("Performance:"),i>0&&_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Parse JSON: ${i.toFixed(2)}ms`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Decode binary: ${c.toFixed(2)}ms`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Create Meshes: ${f.toFixed(2)}ms`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Total: ${p.toFixed(2)}ms`)}return Promise.resolve(C)}function Be(e,r,n,t){let o=new Float32Array(e.length),a=r[0],i=r[1],c=r[2],l=n[0],h=n[1],m=n[2];if(t)for(let u=0;u<e.length;u+=3){let E=a+(e[u]+32767)*l,g=i+(e[u+1]+32767)*h,d=c+(e[u+2]+32767)*m;o[u]=E,o[u+1]=d,o[u+2]=-g}else for(let u=0;u<e.length;u+=3)o[u]=a+(e[u]+32767)*l,o[u+1]=i+(e[u+1]+32767)*h,o[u+2]=c+(e[u+2]+32767)*m;return o}function Le(e,r){if(!r)return e;let n=new Float32Array(e.length);for(let t=0;t<e.length;t+=3){let o=e[t],a=e[t+1],i=e[t+2];n[t]=o,n[t+1]=i,n[t+2]=-a}return n}function Ie(e){let r=N(e.color);return new M.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:M.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function Oe(e,r,n,t){let o=0,a=0;for(let d of e.meshes)o+=d.vertexCount,a+=d.indexCount;let i=new Float32Array(o*3),c=new Uint32Array(a),l=0,h=0;for(let d of e.meshes){let H=d.vertexStart*3,L=d.vertexCount*3;i.set(r.subarray(H,H+L),l*3);let x=n.subarray(d.indexStart,d.indexStart+d.indexCount),C=l-d.vertexStart;if(C===0)c.set(x,h);else for(let f=0;f<x.length;f++)c[h+f]=x[f]+C;l+=d.vertexCount,h+=d.indexCount}let m=new M.BufferGeometry;m.setAttribute("position",new M.BufferAttribute(i,3)),m.setIndex(new M.BufferAttribute(c,1)),m.computeVertexNormals();let u=new M.Mesh(m,t[e.materialId]),E=e.meshes[0],g=e.meshes.map(d=>d.name).filter(d=>d&&d.length>0);return u.name=g.length>0?g[0]:`merged_material_${e.materialId}`,u.castShadow=!0,u.receiveShadow=!0,u.userData={name:u.name,layer:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _144 => _144.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _145 => _145.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _146 => _146.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(d=>({name:d.name,layer:d.layer,originalIndex:d.originalIndex}))},u}function De(e,r,n,t){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,c=a.vertexCount*3,l=r.slice(i,i+c),h=n.subarray(a.indexStart,a.indexStart+a.indexCount),m=new Uint32Array(h.length),u=a.vertexStart;for(let d=0;d<h.length;d++)m[d]=h[d]-u;let E=new M.BufferGeometry;E.setAttribute("position",new M.BufferAttribute(l,3)),E.setIndex(new M.BufferAttribute(m,1)),E.computeVertexNormals();let g=new M.Mesh(E,t[e.materialId]);g.name=a.name,g.userData={name:a.name,layer:_nullishCoalesce(a.layer, () => ("")),originalIndex:a.originalIndex,metadata:_nullishCoalesce(a.metadata, () => ({}))},g.castShadow=!0,g.receiveShadow=!0,o.push(g)}return o}function Fe(e){return Math.floor(e.length*3/4)}var Pe={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},ze="Display";async function ut(e,r){let n=performance.now(),t=[],{allowScaling:o=!0,allowAutoPosition:a=!0,debug:i=!1,parsing:c={}}=_nullishCoalesce(r, () => ({}));try{let l=o?ke(e.modelunits):1;return await Ue(e,t,l,c,i),a&&Ve(t),t}catch(l){throw Ne(l,t),l}finally{i&&$e(n)}}function ke(e){return _nullishCoalesce(Pe[e], () => (1))}async function Ue(e,r,n,t,o){for(let a of e.values){let i=a.InnerTree;for(let c in i){let l=i[c];l&&await _e(l,r,n,t,o)}}}async function _e(e,r,n,t,o){for(let a of e)if(a.type.includes(ze)){let i={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...t},c=await Z(a.data,i);if(n!==1)for(let l of c)l.scale.set(n,n,n);r.push(...c),o&&_chunkRBNF6MNHcjs.e.call(void 0, ).debug(`Extracted ${c.length} meshes from batch`)}}function Ve(e){if(e.length===0)return;let n=z(e).min.y;G(e,n)}function Ne(e,r){_chunkRBNF6MNHcjs.e.call(void 0, ).error("An unexpected error occurred:",e),Ge(r)}function Ge(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(n=>n.dispose()):r.material.dispose())}function $e(e){let r=performance.now()-e;_chunkRBNF6MNHcjs.e.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.a = Ze; exports.b = Xe; exports.c = N; exports.d = G; exports.e = z; exports.f = Me; exports.g = $; exports.h = W; exports.i = k; exports.j = U; exports.k = Z; exports.l = Ae; exports.m = at; exports.n = Pe; exports.o = ut;
|
|
2
|
-
//# sourceMappingURL=chunk-SVEXPGHW.cjs.map
|