@luma.gl/engine 9.4.0-alpha.2 → 9.4.0-alpha.3
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/dist.dev.js +31 -12
- package/dist/dist.min.js +8 -8
- package/dist/index.cjs +31 -12
- package/dist/index.cjs.map +2 -2
- package/dist/model/model.d.ts +1 -1
- package/dist/model/model.d.ts.map +1 -1
- package/dist/passes/shader-pass-renderer.d.ts +13 -1
- package/dist/passes/shader-pass-renderer.d.ts.map +1 -1
- package/dist/passes/shader-pass-renderer.js +31 -12
- package/dist/passes/shader-pass-renderer.js.map +1 -1
- package/package.json +2 -2
- package/src/model/model.ts +1 -1
- package/src/passes/shader-pass-renderer.ts +43 -12
package/dist/index.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts", "../src/animation/animator.ts", "../src/animation/timeline.ts", "../src/animation/key-frames.ts", "../src/animation-loop/animation-loop-template.ts", "../src/animation-loop/animation-loop.ts", "../src/animation-loop/request-animation-frame.ts", "../src/animation-loop/make-animation-loop.ts", "../src/model/model.ts", "../src/geometry/gpu-geometry.ts", "../src/geometry/geometry.ts", "../src/utils/uid.ts", "../src/geometry/geometry-utils.ts", "../src/debug/debug-shader-layout.ts", "../src/debug/debug-framebuffer.ts", "../src/utils/deep-equal.ts", "../src/utils/buffer-layout-helper.ts", "../src/utils/buffer-layout-order.ts", "../src/utils/shader-module-utils.ts", "../src/shader-inputs.ts", "../src/model/split-uniforms-and-bindings.ts", "../src/dynamic-buffer/dynamic-buffer.ts", "../src/dynamic-texture/texture-binding-source.ts", "../src/material/material.ts", "../src/material/material-factory.ts", "../src/compute/buffer-transform.ts", "../src/compute/texture-transform.ts", "../src/models/clip-space.ts", "../src/dynamic-texture/dynamic-texture.ts", "../src/dynamic-texture/texture-data.ts", "../src/models/billboard-texture-model.ts", "../src/geometries/sphere-geometry.ts", "../src/models/light-model-utils.ts", "../src/models/point-light-model.ts", "../src/geometries/truncated-cone-geometry.ts", "../src/geometries/cone-geometry.ts", "../src/models/spot-light-model.ts", "../src/models/directional-light-model.ts", "../src/scenegraph/scenegraph-node.ts", "../src/scenegraph/group-node.ts", "../src/scenegraph/scenegraph-bounds.ts", "../src/scenegraph/model-node.ts", "../src/geometries/cube-geometry.ts", "../src/geometries/cylinder-geometry.ts", "../src/geometries/ico-sphere-geometry.ts", "../src/geometries/plane-geometry.ts", "../src/application-utils/random.ts", "../src/application-utils/load-file.ts", "../src/dynamic-texture/video-texture.ts", "../src/passes/shader-pass-renderer.ts", "../src/compute/swap.ts", "../src/passes/get-fragment-shader.ts", "../src/passes/texture-transform-module.ts", "../src/compute/computation.ts", "../src/modules/picking/picking-manager.ts", "../src/modules/picking/picking-uniforms.ts", "../src/modules/picking/color-picking.ts", "../src/modules/picking/index-color-picking.ts", "../src/modules/picking/index-picking.ts", "../src/modules/picking/picking.ts", "../src/modules/picking/legacy-picking-manager.ts", "../src/modules/picking/legacy-color-picking.ts"],
|
|
4
|
-
"sourcesContent": ["// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// luma.gl Engine API\n\n// Animation\nexport type {AnimationClipControllerProps} from './animation/animator';\nexport {AnimationClipController, Animator} from './animation/animator';\nexport {Timeline} from './animation/timeline';\nexport {KeyFrames} from './animation/key-frames';\nexport type {AnimationProps} from './animation-loop/animation-props';\n\nexport {AnimationLoopTemplate} from './animation-loop/animation-loop-template';\n\nexport type {\n AnimationFrameCallback,\n AnimationFrameProvider,\n AnimationLoopProps\n} from './animation-loop/animation-loop';\nexport {AnimationLoop} from './animation-loop/animation-loop';\n\nexport type {MakeAnimationLoopProps} from './animation-loop/make-animation-loop';\nexport {makeAnimationLoop} from './animation-loop/make-animation-loop';\n\nexport type {ModelProps} from './model/model';\nexport {Model} from './model/model';\nexport type {MaterialProps} from './material/material';\nexport {Material} from './material/material';\nexport type {MaterialFactoryProps} from './material/material-factory';\nexport {MaterialFactory} from './material/material-factory';\n\n// Transforms\nexport type {BufferTransformProps} from './compute/buffer-transform';\nexport {BufferTransform} from './compute/buffer-transform';\nexport type {TextureTransformProps} from './compute/texture-transform';\nexport {TextureTransform} from './compute/texture-transform';\n\n// Models\nexport type {ClipSpaceProps} from './models/clip-space';\nexport {ClipSpace} from './models/clip-space';\nexport type {BackgroundTextureModelProps} from './models/billboard-texture-model';\nexport {BackgroundTextureModel} from './models/billboard-texture-model';\nexport type {\n BaseLightModelProps,\n PointLightModelProps,\n SpotLightModelProps,\n DirectionalLightModelProps\n} from './models/light-model-utils';\nexport {PointLightModel} from './models/point-light-model';\nexport {SpotLightModel} from './models/spot-light-model';\nexport {DirectionalLightModel} from './models/directional-light-model';\n\n// Scenegraph Core nodes\nexport {ScenegraphNode} from './scenegraph/scenegraph-node';\nexport type {ScenegraphBounds} from './scenegraph/scenegraph-bounds';\nexport type {\n DepthSortedTraversalContext,\n DepthSortedTraversalOptions,\n GroupNodeProps\n} from './scenegraph/group-node';\nexport {GroupNode} from './scenegraph/group-node';\nexport type {ModelNodeProps} from './scenegraph/model-node';\nexport {ModelNode} from './scenegraph/model-node';\n\n// Geometries\nexport type {GeometryProps, GeometryAttribute, GeometryAttributeInput} from './geometry/geometry';\nexport {Geometry} from './geometry/geometry';\nexport type {MakeInterleavedGeometryOptions} from './geometry/geometry-utils';\nexport {makeInterleavedGeometry} from './geometry/geometry-utils';\nexport type {GPUGeometryProps} from './geometry/gpu-geometry';\nexport {GPUGeometry} from './geometry/gpu-geometry';\n\n// Primitives\nexport type {ConeGeometryProps} from './geometries/cone-geometry';\nexport {ConeGeometry} from './geometries/cone-geometry';\nexport type {CubeGeometryProps} from './geometries/cube-geometry';\nexport {CubeGeometry} from './geometries/cube-geometry';\nexport type {CylinderGeometryProps} from './geometries/cylinder-geometry';\nexport {CylinderGeometry} from './geometries/cylinder-geometry';\nexport type {IcoSphereGeometryProps} from './geometries/ico-sphere-geometry';\nexport {IcoSphereGeometry} from './geometries/ico-sphere-geometry';\nexport type {PlaneGeometryProps} from './geometries/plane-geometry';\nexport {PlaneGeometry} from './geometries/plane-geometry';\nexport type {SphereGeometryProps} from './geometries/sphere-geometry';\nexport {SphereGeometry} from './geometries/sphere-geometry';\nexport type {TruncatedConeGeometryProps} from './geometries/truncated-cone-geometry';\nexport {TruncatedConeGeometry} from './geometries/truncated-cone-geometry';\n\nexport {ShaderInputs} from './shader-inputs';\nexport type {ShaderInputBinding, ShaderInputsProps} from './shader-inputs';\n\n// Application Utilities\nexport {makeRandomGenerator} from './application-utils/random';\nexport {\n setPathPrefix,\n loadImage,\n loadImageBitmap,\n _resolveLoadFileUrl\n} from './application-utils/load-file';\n\n// Dynamic Resources\n\nexport type {\n TextureCubeFace,\n TextureImageData,\n Texture1DData,\n Texture2DData,\n Texture3DData,\n TextureCubeData,\n TextureArrayData,\n TextureCubeArrayData\n} from './dynamic-texture/texture-data';\n\nexport type {DynamicTextureProps} from './dynamic-texture/dynamic-texture';\nexport {DynamicTexture} from './dynamic-texture/dynamic-texture';\nexport type {\n TextureBindingLayout,\n TextureBindingSource\n} from './dynamic-texture/texture-binding-source';\nexport type {VideoTextureProps} from './dynamic-texture/video-texture';\nexport {VideoTexture} from './dynamic-texture/video-texture';\nexport type {\n BufferBindingSource,\n DynamicBufferProps,\n DynamicBufferRange\n} from './dynamic-buffer/dynamic-buffer';\nexport {DynamicBuffer} from './dynamic-buffer/dynamic-buffer';\n\n// EXPERIMENTAL\nexport type {\n ShaderPassBinding,\n ShaderPassRendererProps,\n ShaderPassRendererRenderOptions,\n ShaderPassSourceTexture\n} from './passes/shader-pass-renderer';\nexport {ShaderPassRenderer} from './passes/shader-pass-renderer';\n\nexport {Swap} from './compute/swap';\nexport {SwapBuffers} from './compute/swap';\nexport {SwapFramebuffers} from './compute/swap';\n\nexport type {ComputationProps} from './compute/computation';\nexport {Computation} from './compute/computation';\n\nexport type {\n PickInfo,\n PickingTooltip,\n PickingMode,\n ResolvedPickingMode,\n PickingShouldPickOptions,\n PickingBackend,\n PickingManagerProps,\n ResolvedPickingBackend\n} from './modules/picking/picking-manager';\nexport {\n PickingManager,\n supportsIndexPicking,\n resolvePickingMode,\n resolvePickingBackend\n} from './modules/picking/picking-manager';\nexport {getIndexPickingModule, picking} from './modules/picking/picking';\nexport {picking as indexPicking} from './modules/picking/index-picking';\nexport {picking as indexColorPicking} from './modules/picking/index-color-picking';\nexport {picking as colorPicking} from './modules/picking/color-picking';\n\nexport {\n requestAnimationFramePolyfill,\n cancelAnimationFramePolyfill\n} from './animation-loop/request-animation-frame';\n\n// DEPRECATED\n\nexport {LegacyPickingManager} from './modules/picking/legacy-picking-manager';\nexport {legacyColorPicking} from './modules/picking/legacy-color-picking';\n\nimport {DynamicTexture, type DynamicTextureProps} from './dynamic-texture/dynamic-texture';\n/** @deprecated use DynamicTexture */\nexport const AsyncTexture = DynamicTexture;\n/** @deprecated use DynamicTextureProps */\nexport type AsyncTextureProps = DynamicTextureProps;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '@luma.gl/core';\n\n/** Construction props shared by all animation clip controllers. */\nexport type AnimationClipControllerProps = {\n /** Application-visible clip name. */\n name?: string;\n /** Start time in seconds relative to wall-clock playback time. */\n startTime?: number;\n /** Whether playback is active. */\n playing?: boolean;\n /** Playback speed multiplier. */\n speed?: number;\n};\n\n/** Generic playback controller for one animation clip. */\nexport abstract class AnimationClipController {\n /** Application-visible clip name. */\n name: string;\n /** Whether playback is currently enabled. */\n playing: boolean = true;\n /** Playback speed multiplier. */\n speed: number = 1;\n /** Start time in seconds relative to wall-clock playback time. */\n startTime: number = 0;\n\n constructor(props: AnimationClipControllerProps = {}) {\n this.name = props.name || 'unnamed';\n Object.assign(this, props);\n }\n\n /** Advances the clip to the supplied wall-clock time in milliseconds. */\n setTime(timeMs: number): void {\n if (!this.playing) {\n return;\n }\n\n const absoluteTimeSeconds = timeMs / 1000;\n const localTimeSeconds = (absoluteTimeSeconds - this.startTime) * this.speed;\n this.applyTime(localTimeSeconds);\n }\n\n /** Applies the resolved local clip time in seconds. */\n protected abstract applyTime(localTimeSeconds: number): void;\n}\n\n/** Generic manager for a set of time-driven animation clips. */\nexport class Animator<TClip extends AnimationClipController> {\n /** Managed clip list. */\n readonly clips: TClip[];\n /** Compatibility alias for clip list. */\n readonly animations: TClip[];\n\n constructor(clips: TClip[]) {\n this.clips = clips;\n this.animations = clips;\n }\n\n /** @deprecated Use .setTime(). */\n animate(timeMs: number): void {\n log.warn(\n `${this.constructor.name}#animate is deprecated. Use ${this.constructor.name}#setTime instead`\n )();\n this.setTime(timeMs);\n }\n\n /** Advances every clip to the supplied wall-clock time in milliseconds. */\n setTime(timeMs: number): void {\n this.clips.forEach(clip => clip.setTime(timeMs));\n }\n\n /** Returns the managed animation clips. */\n getAnimations(): TClip[] {\n return this.clips;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Timeline channel properties\n * @param delay = 0;\n * @param duration = Number.POSITIVE_INFINITY;\n * @param rate = 1\n * @param repeat = 1\n */\nexport type ChannelOptions = {\n delay?: number;\n duration?: number;\n rate?: number;\n repeat?: number;\n};\n\nexport type AnimationOptions = {\n setTime: (time: number) => void;\n};\n\ntype Channel = {\n time: number;\n delay: number;\n duration: number;\n rate: number;\n repeat: number;\n};\n\ntype Animation = {\n channel?: number;\n animation: {\n setTime: (time: number) => void;\n };\n};\n\nlet channelHandles = 1;\nlet animationHandles = 1;\n\nexport class Timeline {\n time: number = 0;\n channels = new Map<number, Channel>();\n animations = new Map<number, Animation>();\n playing: boolean = false;\n lastEngineTime: number = -1;\n\n constructor() {}\n\n addChannel(props: ChannelOptions): number {\n const {delay = 0, duration = Number.POSITIVE_INFINITY, rate = 1, repeat = 1} = props;\n\n const channelId = channelHandles++;\n const channel: Channel = {\n time: 0,\n delay,\n duration,\n rate,\n repeat\n };\n this._setChannelTime(channel, this.time);\n this.channels.set(channelId, channel);\n\n return channelId;\n }\n\n removeChannel(channelId: number): void {\n this.channels.delete(channelId);\n\n for (const [animationHandle, animation] of this.animations) {\n if (animation.channel === channelId) {\n this.detachAnimation(animationHandle);\n }\n }\n }\n\n isFinished(channelId: number): boolean {\n const channel = this.channels.get(channelId);\n if (channel === undefined) {\n return false;\n }\n\n return this.time >= channel.delay + channel.duration * channel.repeat;\n }\n\n getTime(channelId?: number): number {\n if (channelId === undefined) {\n return this.time;\n }\n\n const channel = this.channels.get(channelId);\n\n if (channel === undefined) {\n return -1;\n }\n\n return channel.time;\n }\n\n setTime(time: number): void {\n this.time = Math.max(0, time);\n\n const channels = this.channels.values();\n for (const channel of channels) {\n this._setChannelTime(channel, this.time);\n }\n\n const animations = this.animations.values();\n for (const animationData of animations) {\n const {animation, channel} = animationData;\n animation.setTime(this.getTime(channel));\n }\n }\n\n play(): void {\n this.playing = true;\n }\n\n pause(): void {\n this.playing = false;\n this.lastEngineTime = -1;\n }\n\n reset(): void {\n this.setTime(0);\n }\n\n attachAnimation(animation: AnimationOptions, channelHandle?: number): number {\n const animationHandle = animationHandles++;\n\n this.animations.set(animationHandle, {\n animation,\n channel: channelHandle\n });\n\n animation.setTime(this.getTime(channelHandle));\n\n return animationHandle;\n }\n\n detachAnimation(channelId: number): void {\n this.animations.delete(channelId);\n }\n\n update(engineTime: number): void {\n if (this.playing) {\n if (this.lastEngineTime === -1) {\n this.lastEngineTime = engineTime;\n }\n this.setTime(this.time + (engineTime - this.lastEngineTime));\n this.lastEngineTime = engineTime;\n }\n }\n\n _setChannelTime(channel: Channel, time: number): void {\n const offsetTime = time - channel.delay;\n const totalDuration = channel.duration * channel.repeat;\n // Note(Tarek): Don't loop on final repeat.\n if (offsetTime >= totalDuration) {\n channel.time = channel.duration * channel.rate;\n } else {\n channel.time = Math.max(0, offsetTime) % channel.duration;\n channel.time *= channel.rate;\n }\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// keyframes\nexport type KeyFrame<T> = [number, T];\n\n/** Holds a list of key frames (timestamped values) */\nexport class KeyFrames<T = number> {\n startIndex: number = -1;\n endIndex: number = -1;\n factor: number = 0;\n times: number[] = [];\n values: T[] = [];\n private _lastTime = -1;\n\n constructor(keyFrames: KeyFrame<T>[]) {\n this.setKeyFrames(keyFrames);\n this.setTime(0);\n }\n\n setKeyFrames(keyFrames: KeyFrame<T>[]): void {\n const numKeys = keyFrames.length;\n this.times.length = numKeys;\n this.values.length = numKeys;\n\n for (let i = 0; i < numKeys; ++i) {\n this.times[i] = keyFrames[i][0];\n this.values[i] = keyFrames[i][1];\n }\n\n this._calculateKeys(this._lastTime);\n }\n\n setTime(time: number): void {\n time = Math.max(0, time);\n\n if (time !== this._lastTime) {\n this._calculateKeys(time);\n this._lastTime = time;\n }\n }\n\n getStartTime(): number {\n return this.times[this.startIndex];\n }\n\n getEndTime(): number {\n return this.times[this.endIndex];\n }\n\n getStartData(): T {\n return this.values[this.startIndex];\n }\n\n getEndData(): T {\n return this.values[this.endIndex];\n }\n\n _calculateKeys(time: number): void {\n let index = 0;\n const numKeys = this.times.length;\n\n for (index = 0; index < numKeys - 2; ++index) {\n if (this.times[index + 1] > time) {\n break;\n }\n }\n\n this.startIndex = index;\n this.endIndex = index + 1;\n\n const startTime = this.times[this.startIndex];\n const endTime = this.times[this.endIndex];\n this.factor = Math.min(Math.max(0, (time - startTime) / (endTime - startTime)), 1);\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {AnimationProps} from './animation-props';\n\n/**\n * Minimal class that represents a \"componentized\" rendering life cycle\n * (resource construction, repeated rendering, resource destruction)\n *\n * @note A motivation for this class compared to the raw animation loop is\n * that it simplifies TypeScript code by allowing resources to be typed unconditionally\n * since they are allocated in the constructor rather than in onInitialized\n *\n * @note Introduced in luma.gl v9\n *\n * @example AnimationLoopTemplate is intended to be subclassed,\n * but the subclass should not be instantiated directly. Instead the subclass\n * (i.e. the constructor of the subclass) should be used\n * as an argument to create an AnimationLoop.\n */\nexport abstract class AnimationLoopTemplate {\n constructor(animationProps?: AnimationProps) {}\n async onInitialize(animationProps: AnimationProps): Promise<unknown> {\n return null;\n }\n abstract onRender(animationProps: AnimationProps): unknown;\n abstract onFinalize(animationProps: AnimationProps): void;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {luma, Device} from '@luma.gl/core';\nimport {\n requestAnimationFramePolyfill,\n cancelAnimationFramePolyfill\n} from './request-animation-frame';\nimport {Timeline} from '../animation/timeline';\nimport {AnimationProps} from './animation-props';\nimport {Stats, Stat} from '@probe.gl/stats';\n\nlet statIdCounter = 0;\nconst ANIMATION_LOOP_STATS = 'Animation Loop';\n\n/** Experimental v10 callback shape for browser or custom animation frames. */\nexport type AnimationFrameCallback = (time: DOMHighResTimeStamp, animationFrame?: unknown) => void;\n\n/** Experimental v10 work-in-progress animation frame source. */\nexport interface AnimationFrameProvider {\n requestAnimationFrame(callback: AnimationFrameCallback): number;\n cancelAnimationFrame(animationFrameId: number): void;\n}\n\nconst defaultAnimationFrameProvider: AnimationFrameProvider = {\n requestAnimationFrame: callback => requestAnimationFramePolyfill(callback),\n cancelAnimationFrame: animationFrameId => cancelAnimationFramePolyfill(animationFrameId)\n};\n\n/** AnimationLoop properties */\nexport type AnimationLoopProps = {\n device: Device | Promise<Device>;\n\n onAddHTML?: (div: HTMLDivElement) => string; // innerHTML\n onInitialize?: (animationProps: AnimationProps) => Promise<unknown>;\n onRender?: (animationProps: AnimationProps) => unknown;\n onFinalize?: (animationProps: AnimationProps) => void;\n onError?: (reason: Error) => void;\n\n stats?: Stats;\n\n // view parameters - TODO move to CanvasContext?\n autoResizeViewport?: boolean;\n /** Experimental v10 work-in-progress frame source. */\n animationFrameProvider?: AnimationFrameProvider;\n};\n\nexport type MutableAnimationLoopProps = {\n // view parameters\n autoResizeViewport?: boolean;\n /** Experimental v10 work-in-progress frame source. */\n animationFrameProvider?: AnimationFrameProvider;\n};\n\n/** Convenient animation loop */\nexport class AnimationLoop {\n static defaultAnimationLoopProps = {\n device: null!,\n\n onAddHTML: () => '',\n onInitialize: async () => null,\n onRender: () => {},\n onFinalize: () => {},\n onError: error => {\n // biome-ignore lint/suspicious/noConsole: default fallback error reporting for app loops.\n console.error(error);\n },\n\n stats: undefined!,\n\n // view parameters\n autoResizeViewport: false,\n animationFrameProvider: defaultAnimationFrameProvider\n } as const satisfies Readonly<Required<AnimationLoopProps>>;\n\n device: Device | null = null;\n canvas: HTMLCanvasElement | OffscreenCanvas | null = null;\n\n props: Required<AnimationLoopProps>;\n animationProps: AnimationProps | null = null;\n timeline: Timeline | null = null;\n stats: Stats;\n sharedStats: Stats;\n cpuTime: Stat;\n gpuTime: Stat;\n frameRate: Stat;\n\n display: any;\n\n private _needsRedraw: string | false = 'initialized';\n\n _initialized: boolean = false;\n _running: boolean = false;\n _animationFrameId: any = null;\n _nextFramePromise: Promise<AnimationLoop> | null = null;\n _resolveNextFrame: ((animationLoop: AnimationLoop) => void) | null = null;\n _cpuStartTime: number = 0;\n _error: Error | null = null;\n _lastFrameTime: number = 0;\n\n /*\n * @param {HTMLCanvasElement} canvas - if provided, width and height will be passed to context\n */\n constructor(props: AnimationLoopProps) {\n this.props = {...AnimationLoop.defaultAnimationLoopProps, ...props};\n props = this.props;\n\n if (!props.device) {\n throw new Error('No device provided');\n }\n\n // state\n this.stats = props.stats || new Stats({id: `animation-loop-${statIdCounter++}`});\n this.sharedStats = luma.stats.get(ANIMATION_LOOP_STATS);\n this.frameRate = this.stats.get('Frame Rate');\n this.frameRate.setSampleSize(1);\n this.cpuTime = this.stats.get('CPU Time');\n this.gpuTime = this.stats.get('GPU Time');\n\n this.setProps({\n autoResizeViewport: props.autoResizeViewport,\n animationFrameProvider: props.animationFrameProvider\n });\n\n // Bind methods\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n\n this._onMousemove = this._onMousemove.bind(this);\n this._onMouseleave = this._onMouseleave.bind(this);\n }\n\n destroy(): void {\n this.stop();\n this._setDisplay(null);\n this.device?._disableDebugGPUTime();\n }\n\n /** @deprecated Use .destroy() */\n delete(): void {\n this.destroy();\n }\n\n reportError(error: Error): void {\n this.props.onError(error);\n this._error = error;\n }\n\n /** Flags this animation loop as needing redraw */\n setNeedsRedraw(reason: string): this {\n this._needsRedraw = this._needsRedraw || reason;\n return this;\n }\n\n /** Query redraw status. Clears the flag. */\n needsRedraw(): false | string {\n const reason = this._needsRedraw;\n this._needsRedraw = false;\n return reason;\n }\n\n setProps(props: MutableAnimationLoopProps): this {\n if ('autoResizeViewport' in props) {\n this.props.autoResizeViewport = props.autoResizeViewport || false;\n }\n if ('animationFrameProvider' in props) {\n const animationFrameProvider = props.animationFrameProvider || defaultAnimationFrameProvider;\n if (animationFrameProvider !== this.props.animationFrameProvider) {\n const animationFrameWasScheduled = this._animationFrameId !== null;\n if (animationFrameWasScheduled) {\n this._cancelAnimationFrame();\n }\n this.props.animationFrameProvider = animationFrameProvider;\n if (animationFrameWasScheduled) {\n this._requestAnimationFrame();\n }\n }\n }\n return this;\n }\n\n /** Starts a render loop if not already running */\n async start() {\n if (this._running) {\n return this;\n }\n this._running = true;\n\n try {\n let appContext;\n if (!this._initialized) {\n this._initialized = true;\n // Create the WebGL context\n await this._initDevice();\n this._initialize();\n if (!this._running) {\n return null;\n }\n\n // Note: onIntialize can return a promise (e.g. in case app needs to load resources)\n await this.props.onInitialize(this._getAnimationProps());\n }\n\n // check that we haven't been stopped\n if (!this._running) {\n return null;\n }\n\n // Start the loop\n if (appContext !== false) {\n // cancel any pending renders to ensure only one loop can ever run\n this._cancelAnimationFrame();\n this._requestAnimationFrame();\n }\n\n return this;\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error('Unknown error');\n this.props.onError(error);\n // this._running = false; // TODO\n throw error;\n }\n }\n\n /** Stops a render loop if already running, finalizing */\n stop() {\n // console.debug(`Stopping ${this.constructor.name}`);\n if (this._running) {\n // call callback\n // If stop is called immediately, we can end up in a state where props haven't been initialized...\n if (this.animationProps && !this._error) {\n this.props.onFinalize(this.animationProps);\n }\n\n this._cancelAnimationFrame();\n this._nextFramePromise = null;\n this._resolveNextFrame = null;\n this._running = false;\n this._lastFrameTime = 0;\n }\n return this;\n }\n\n /** Explicitly draw a frame */\n redraw(time?: number, animationFrame: unknown | null = null): this {\n if (this.device?.isLost || this._error) {\n return this;\n }\n\n this._beginFrameTimers(time);\n\n this._setupFrame();\n if (this.animationProps) {\n this.animationProps.animationFrame = animationFrame;\n }\n this._updateAnimationProps();\n\n this._renderFrame(this._getAnimationProps());\n\n // clear needsRedraw flag\n this._clearNeedsRedraw();\n\n if (this._resolveNextFrame) {\n this._resolveNextFrame(this);\n this._nextFramePromise = null;\n this._resolveNextFrame = null;\n }\n\n this._endFrameTimers();\n\n return this;\n }\n\n /** Add a timeline, it will be automatically updated by the animation loop. */\n attachTimeline(timeline: Timeline): Timeline {\n this.timeline = timeline;\n return this.timeline;\n }\n\n /** Remove a timeline */\n detachTimeline(): void {\n this.timeline = null;\n }\n\n /** Wait until a render completes */\n waitForRender(): Promise<AnimationLoop> {\n this.setNeedsRedraw('waitForRender');\n\n if (!this._nextFramePromise) {\n this._nextFramePromise = new Promise(resolve => {\n this._resolveNextFrame = resolve;\n });\n }\n return this._nextFramePromise;\n }\n\n /** TODO - should use device.deviceContext */\n async toDataURL(): Promise<string> {\n this.setNeedsRedraw('toDataURL');\n await this.waitForRender();\n if (this.canvas instanceof HTMLCanvasElement) {\n return this.canvas.toDataURL();\n }\n throw new Error('OffscreenCanvas');\n }\n\n // PRIVATE METHODS\n\n _initialize(): void {\n this._startEventHandling();\n\n // Initialize the callback data\n this._initializeAnimationProps();\n this._updateAnimationProps();\n\n // Default viewport setup, in case onInitialize wants to render\n this._resizeViewport();\n\n this.device?._enableDebugGPUTime();\n }\n\n _setDisplay(display: any): void {\n if (this.display) {\n this.display.destroy();\n this.display.animationLoop = null;\n }\n\n // store animation loop on the display\n if (display) {\n display.animationLoop = this;\n }\n\n this.display = display;\n }\n\n _requestAnimationFrame(): void {\n if (!this._running) {\n return;\n }\n\n this._animationFrameId = this.props.animationFrameProvider.requestAnimationFrame(\n this._animationFrame.bind(this)\n );\n }\n\n _cancelAnimationFrame(): void {\n if (this._animationFrameId === null) {\n return;\n }\n\n this.props.animationFrameProvider.cancelAnimationFrame(this._animationFrameId);\n this._animationFrameId = null;\n }\n\n _animationFrame(time: number, animationFrame?: unknown): void {\n if (!this._running) {\n return;\n }\n this.redraw(time, animationFrame ?? null);\n this._requestAnimationFrame();\n }\n\n // Called on each frame, can be overridden to call onRender multiple times\n // to support e.g. stereoscopic rendering\n _renderFrame(animationProps: AnimationProps): void {\n // Allow e.g. VR display to render multiple frames.\n if (this.display) {\n this.display._renderFrame(animationProps);\n return;\n }\n\n // call callback\n this.props.onRender(this._getAnimationProps());\n // end callback\n\n // Submit commands (necessary on WebGPU).\n if (this.device) {\n this.device.submit();\n }\n }\n\n _clearNeedsRedraw(): void {\n this._needsRedraw = false;\n }\n\n _setupFrame(): void {\n this._resizeViewport();\n }\n\n // Initialize the object that will be passed to app callbacks\n _initializeAnimationProps(): void {\n const canvasContext = this.device?.getDefaultCanvasContext();\n if (!this.device || !canvasContext) {\n throw new Error('loop');\n }\n\n const canvas = canvasContext?.canvas;\n const useDevicePixels = canvasContext.props.useDevicePixels;\n\n this.animationProps = {\n animationLoop: this,\n\n device: this.device,\n canvasContext,\n canvas,\n // @ts-expect-error Deprecated\n useDevicePixels,\n\n timeline: this.timeline,\n\n needsRedraw: false,\n\n // Placeholders\n width: 1,\n height: 1,\n aspect: 1,\n\n // Animation props\n time: 0,\n startTime: Date.now(),\n engineTime: 0,\n tick: 0,\n tock: 0,\n\n // Experimental\n animationFrame: null,\n _mousePosition: null // Event props\n };\n }\n\n _getAnimationProps(): AnimationProps {\n if (!this.animationProps) {\n throw new Error('animationProps');\n }\n return this.animationProps;\n }\n\n // Update the context object that will be passed to app callbacks\n _updateAnimationProps(): void {\n if (!this.animationProps) {\n return;\n }\n\n // Can this be replaced with canvas context?\n const {width, height, aspect} = this._getSizeAndAspect();\n if (width !== this.animationProps.width || height !== this.animationProps.height) {\n this.setNeedsRedraw('drawing buffer resized');\n }\n if (aspect !== this.animationProps.aspect) {\n this.setNeedsRedraw('drawing buffer aspect changed');\n }\n\n this.animationProps.width = width;\n this.animationProps.height = height;\n this.animationProps.aspect = aspect;\n\n this.animationProps.needsRedraw = this._needsRedraw;\n\n // Update time properties\n this.animationProps.engineTime = Date.now() - this.animationProps.startTime;\n\n if (this.timeline) {\n this.timeline.update(this.animationProps.engineTime);\n }\n\n this.animationProps.tick = Math.floor((this.animationProps.time / 1000) * 60);\n this.animationProps.tock++;\n\n // For back compatibility\n this.animationProps.time = this.timeline\n ? this.timeline.getTime()\n : this.animationProps.engineTime;\n }\n\n /** Wait for supplied device */\n async _initDevice() {\n this.device = await this.props.device;\n if (!this.device) {\n throw new Error('No device provided');\n }\n this.canvas = this.device.getDefaultCanvasContext().canvas || null;\n // this._createInfoDiv();\n }\n\n _createInfoDiv(): void {\n if (this.canvas && this.props.onAddHTML) {\n const wrapperDiv = document.createElement('div');\n document.body.appendChild(wrapperDiv);\n wrapperDiv.style.position = 'relative';\n const div = document.createElement('div');\n div.style.position = 'absolute';\n div.style.left = '10px';\n div.style.bottom = '10px';\n div.style.width = '300px';\n div.style.background = 'white';\n if (this.canvas instanceof HTMLCanvasElement) {\n wrapperDiv.appendChild(this.canvas);\n }\n wrapperDiv.appendChild(div);\n const html = this.props.onAddHTML(div);\n if (html) {\n div.innerHTML = html;\n }\n }\n }\n\n _getSizeAndAspect(): {width: number; height: number; aspect: number} {\n if (!this.device) {\n return {width: 1, height: 1, aspect: 1};\n }\n // Match projection setup to the actual render target dimensions, which may\n // differ from the CSS size when device-pixel scaling or backend clamping applies.\n const [width, height] = this.device.getDefaultCanvasContext().getDrawingBufferSize();\n const aspect = width > 0 && height > 0 ? width / height : 1;\n\n return {width, height, aspect};\n }\n\n /** @deprecated Default viewport setup */\n _resizeViewport(): void {\n // TODO can we use canvas context to code this in a portable way?\n // @ts-expect-error Expose on canvasContext\n if (this.props.autoResizeViewport && this.device.gl) {\n // @ts-expect-error Expose canvasContext\n this.device.gl.viewport(\n 0,\n 0,\n // @ts-expect-error Expose canvasContext\n this.device.gl.drawingBufferWidth,\n // @ts-expect-error Expose canvasContext\n this.device.gl.drawingBufferHeight\n );\n }\n }\n\n _beginFrameTimers(time?: number) {\n const now = time ?? (typeof performance !== 'undefined' ? performance.now() : Date.now());\n if (this._lastFrameTime) {\n const frameTime = now - this._lastFrameTime;\n if (frameTime > 0) {\n this.frameRate.addTime(frameTime);\n }\n }\n this._lastFrameTime = now;\n\n if (this.device?._isDebugGPUTimeEnabled()) {\n this._consumeEncodedGpuTime();\n }\n\n this.cpuTime.timeStart();\n }\n\n _endFrameTimers() {\n if (this.device?._isDebugGPUTimeEnabled()) {\n this._consumeEncodedGpuTime();\n }\n\n this.cpuTime.timeEnd();\n this._updateSharedStats();\n }\n\n _consumeEncodedGpuTime(): void {\n if (!this.device) {\n return;\n }\n\n const gpuTimeMs = this.device.commandEncoder._gpuTimeMs;\n if (gpuTimeMs !== undefined) {\n this.gpuTime.addTime(gpuTimeMs);\n this.device.commandEncoder._gpuTimeMs = undefined;\n }\n }\n\n _updateSharedStats(): void {\n if (this.stats === this.sharedStats) {\n return;\n }\n\n for (const name of Object.keys(this.sharedStats.stats)) {\n if (!this.stats.stats[name]) {\n delete this.sharedStats.stats[name];\n }\n }\n\n this.stats.forEach(sourceStat => {\n const targetStat = this.sharedStats.get(sourceStat.name, sourceStat.type);\n targetStat.sampleSize = sourceStat.sampleSize;\n targetStat.time = sourceStat.time;\n targetStat.count = sourceStat.count;\n targetStat.samples = sourceStat.samples;\n targetStat.lastTiming = sourceStat.lastTiming;\n targetStat.lastSampleTime = sourceStat.lastSampleTime;\n targetStat.lastSampleCount = sourceStat.lastSampleCount;\n targetStat._count = sourceStat._count;\n targetStat._time = sourceStat._time;\n targetStat._samples = sourceStat._samples;\n targetStat._startTime = sourceStat._startTime;\n targetStat._timerPending = sourceStat._timerPending;\n });\n }\n\n // Event handling\n\n _startEventHandling() {\n if (this.canvas) {\n this.canvas.addEventListener('mousemove', this._onMousemove.bind(this));\n this.canvas.addEventListener('mouseleave', this._onMouseleave.bind(this));\n }\n }\n\n _onMousemove(event: Event) {\n if (event instanceof MouseEvent) {\n this._getAnimationProps()._mousePosition = [event.offsetX, event.offsetY];\n }\n }\n\n _onMouseleave(event: Event) {\n this._getAnimationProps()._mousePosition = null;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global window, setTimeout, clearTimeout */\n\n/** Node.js polyfill for requestAnimationFrame */\n// / <reference types=\"@types/node\" />\nexport function requestAnimationFramePolyfill(callback: (time?: any) => void): any {\n const browserRequestAnimationFrame =\n typeof window !== 'undefined'\n ? window.requestAnimationFrame ||\n (window as Window & {webkitRequestAnimationFrame?: (cb: FrameRequestCallback) => number})\n .webkitRequestAnimationFrame ||\n (window as Window & {mozRequestAnimationFrame?: (cb: FrameRequestCallback) => number})\n .mozRequestAnimationFrame\n : null;\n\n if (browserRequestAnimationFrame) {\n return browserRequestAnimationFrame.call(window, callback);\n }\n\n return setTimeout(\n () => callback(typeof performance !== 'undefined' ? performance.now() : Date.now()),\n 1000 / 60\n );\n}\n\n/** Node.js polyfill for cancelAnimationFrame */\nexport function cancelAnimationFramePolyfill(timerId: any): void {\n const browserCancelAnimationFrame =\n typeof window !== 'undefined'\n ? window.cancelAnimationFrame ||\n (window as Window & {webkitCancelAnimationFrame?: (handle: number) => void})\n .webkitCancelAnimationFrame ||\n (window as Window & {mozCancelAnimationFrame?: (handle: number) => void})\n .mozCancelAnimationFrame\n : null;\n\n if (browserCancelAnimationFrame) {\n browserCancelAnimationFrame.call(window, timerId);\n return;\n }\n\n clearTimeout(timerId);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {luma, Adapter, Device} from '@luma.gl/core';\nimport {AnimationLoopTemplate} from './animation-loop-template';\nimport {AnimationLoop, AnimationLoopProps} from './animation-loop';\nimport type {AnimationProps} from './animation-props';\n\n/** Props accepted while constructing an animation loop from a template. */\nexport type MakeAnimationLoopProps = Omit<\n AnimationLoopProps,\n 'onCreateDevice' | 'onInitialize' | 'onRedraw' | 'onFinalize'\n> & {\n /** List of adapters to use when creating the device */\n adapters?: Adapter[];\n};\n\n/**\n * Instantiates an animation loop and initializes it with the template.\n * @note The application needs to call `start()` on the returned animation loop to start the rendering loop.\n */\nexport function makeAnimationLoop(\n AnimationLoopTemplateCtor: typeof AnimationLoopTemplate,\n props?: MakeAnimationLoopProps\n): AnimationLoop {\n let renderLoop: AnimationLoopTemplate | null = null;\n\n const device =\n props?.device ||\n luma.createDevice({id: 'animation-loop', adapters: props?.adapters, createCanvasContext: true});\n\n // Create an animation loop;\n const animationLoop = new AnimationLoop({\n ...props,\n\n device,\n\n async onInitialize(animationProps: AnimationProps): Promise<unknown> {\n clearError(animationProps.animationLoop.device);\n try {\n // @ts-expect-error abstract to prevent instantiation\n renderLoop = new AnimationLoopTemplateCtor(animationProps);\n // Any async loading can be handled here\n return await renderLoop?.onInitialize(animationProps);\n } catch (error) {\n // biome-ignore lint/suspicious/noConsole: fallback logging before rendering the in-canvas error banner.\n console.error(error);\n renderLoop = null;\n setError(animationProps.animationLoop.device, error as Error);\n animationProps.animationLoop.stop();\n return null;\n }\n },\n\n onRender: (animationProps: AnimationProps) => renderLoop?.onRender(animationProps),\n\n onFinalize: (animationProps: AnimationProps) => renderLoop?.onFinalize(animationProps)\n });\n\n // @ts-expect-error Hack: adds info for the website to find\n animationLoop.getInfo = () => {\n // @ts-ignore\n // eslint-disable-next-line no-invalid-this\n return this.AnimationLoopTemplateCtor.info;\n };\n\n return animationLoop;\n}\n\nfunction setError(device: Device | null, error: Error): void {\n if (!device) {\n return;\n }\n\n const canvas = device.getDefaultCanvasContext().canvas;\n if (canvas instanceof HTMLCanvasElement) {\n canvas.style.overflow = 'visible';\n let errorDiv = document.getElementById('animation-loop-error');\n errorDiv?.remove();\n errorDiv = document.createElement('h1');\n errorDiv.id = 'animation-loop-error';\n errorDiv.innerHTML = error.message;\n errorDiv.style.position = 'absolute';\n errorDiv.style.top = '10px'; // left: 50%; transform: translate(-50%, -50%);';\n errorDiv.style.left = '10px';\n errorDiv.style.color = 'black';\n errorDiv.style.backgroundColor = 'red';\n canvas.parentElement?.appendChild(errorDiv);\n // canvas.style.position = 'absolute';\n }\n}\n\nfunction clearError(device: Device | null): void {\n if (!device) {\n return;\n }\n\n const errorDiv = document.getElementById('animation-loop-error');\n if (errorDiv) {\n errorDiv.remove();\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// A lot of imports, but then Model is where it all comes together...\nimport {type TypedArray} from '@math.gl/types';\nimport {\n type RenderPipelineProps,\n type RenderPipelineParameters,\n type BufferLayout,\n type TextureFormatColor,\n type TextureFormatDepthStencil,\n type Shader,\n type VertexArray,\n type TransformFeedback,\n type CommandEncoder,\n type AttributeInfo,\n type Binding,\n type BindingsByGroup,\n type ComputeShaderLayout,\n type PrimitiveTopology,\n type ShaderLayout,\n type AttributeShaderType,\n Device,\n DeviceFeature,\n Buffer,\n ExternalTexture,\n Texture,\n TextureView,\n RenderPipeline,\n RenderPass,\n PipelineFactory,\n ShaderFactory,\n UniformStore,\n log,\n dataTypeDecoder,\n getAttributeInfosFromLayouts,\n normalizeBindingsByGroup\n} from '@luma.gl/core';\n\nimport type {\n ShaderBindingDebugRow,\n ShaderModule,\n ShaderPlugin,\n PlatformInfo\n} from '@luma.gl/shadertools';\nimport {\n mergeShaderPluginModules,\n resolveShaderPlugins,\n ShaderAssembler\n} from '@luma.gl/shadertools';\n\nimport type {Geometry} from '../geometry/geometry';\nimport {GPUGeometry, makeGPUGeometry} from '../geometry/gpu-geometry';\nimport {getDebugTableForShaderLayout} from '../debug/debug-shader-layout';\nimport {debugFramebuffer} from '../debug/debug-framebuffer';\nimport {deepEqual} from '../utils/deep-equal';\nimport {BufferLayoutHelper} from '../utils/buffer-layout-helper';\nimport {sortedBufferLayoutByShaderSourceLocations} from '../utils/buffer-layout-order';\nimport {\n mergeInferredShaderLayout,\n mergeShaderModules,\n mergeShaderModuleBindingsIntoLayout,\n shaderModuleHasUniforms\n} from '../utils/shader-module-utils';\nimport {uid} from '../utils/uid';\nimport {ShaderInputs} from '../shader-inputs';\nimport {\n DynamicBuffer,\n type DynamicBufferRange,\n isBufferRangeBinding,\n resolveBufferRangeBinding\n} from '../dynamic-buffer/dynamic-buffer';\nimport {\n getTextureBindingLayout,\n isTextureBindingSource,\n type TextureBindingSource\n} from '../dynamic-texture/texture-binding-source';\nimport {Material} from '../material/material';\n\nconst LOG_DRAW_PRIORITY = 2;\nconst LOG_DRAW_TIMEOUT = 10000;\nconst PIPELINE_INITIALIZATION_FAILED = 'render pipeline initialization failed';\nconst DEPTH_STENCIL_ATTACHMENT_FORMATS: TextureFormatDepthStencil[] = [\n 'stencil8',\n 'depth16unorm',\n 'depth24plus',\n 'depth24plus-stencil8',\n 'depth32float',\n 'depth32float-stencil8'\n];\n/** Resource accepted by one model binding slot. */\ntype ModelBinding = Binding | TextureBindingSource | DynamicBuffer | DynamicBufferRange;\ntype ModelBuffer = Buffer | DynamicBuffer;\n/** Shader layout subset needed while resolving texture binding sources. */\ntype AnyShaderLayout = Pick<ShaderLayout | ComputeShaderLayout, 'bindings'>;\n\nexport type ModelProps = Omit<RenderPipelineProps, 'vs' | 'fs' | 'bindings'> & {\n source?: string;\n vs?: string | null;\n fs?: string | null;\n\n /** Shadertools shader modules added to shader code. */\n modules?: ShaderModule[];\n /** Shadertools boolean or numeric preprocessor defines that configure shader code. */\n defines?: Record<string, boolean | number>;\n /** Reusable shader assembly plugins resolved for the active GLSL or WGSL backend. */\n plugins?: ShaderPlugin[];\n\n /** Shader inputs, used to generate uniform buffers and bindings. */\n shaderInputs?: ShaderInputs;\n /** Material-owned group-3 bindings */\n material?: Material;\n /** Shader resource bindings, including dynamic buffers and dynamic textures. */\n bindings?: Record<string, ModelBinding>;\n /** WebGL-only uniforms */\n uniforms?: Record<string, unknown>;\n /** Parameters that are built into the pipeline */\n parameters?: RenderPipelineParameters;\n\n /** Geometry */\n geometry?: GPUGeometry | Geometry | null;\n\n /** @deprecated Use instanced rendering? Will be auto-detected in 9.1 */\n isInstanced?: boolean;\n /** instance count */\n instanceCount?: number;\n /** Vertex count */\n vertexCount?: number;\n\n /** Optional index buffer. Dynamic buffers are rebound when resized. */\n indexBuffer?: ModelBuffer | null;\n /** Optional indexed draw count. Defaults to the full bound index buffer length. */\n indexCount?: number;\n /** First vertex byte offset for WebGL indexed draws or first vertex for non-indexed draws. */\n firstVertex?: number;\n /** First index element for WebGPU indexed draws. */\n firstIndex?: number;\n /** Buffer-valued attributes. Dynamic buffers are rebound when resized. */\n attributes?: Record<string, ModelBuffer>;\n /** */\n constantAttributes?: Record<string, TypedArray>;\n\n /** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */\n disableWarnings?: boolean;\n\n /** @internal For use with {@link TransformFeedback}, WebGL only. */\n varyings?: string[];\n\n transformFeedback?: TransformFeedback;\n\n /** Show shader source in browser? */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n\n /** Factory used to create a {@link RenderPipeline}. Defaults to {@link Device} default factory. */\n pipelineFactory?: PipelineFactory;\n /** Factory used to create a {@link Shader}. Defaults to {@link Device} default factory. */\n shaderFactory?: ShaderFactory;\n /** Shader assembler. Defaults to the ShaderAssembler.getShaderAssembler() */\n shaderAssembler?: ShaderAssembler;\n};\n\n/**\n * High level draw API for luma.gl.\n *\n * A `Model` encapsulates shaders, geometry attributes, bindings and render\n * pipeline state into a single object. It automatically reuses and rebuilds\n * pipelines as render parameters change and exposes convenient hooks for\n * updating uniforms and attributes.\n *\n * Features:\n * - Reuses and lazily recompiles {@link RenderPipeline | pipelines} as needed.\n * - Integrates with `@luma.gl/shadertools` to assemble GLSL or WGSL from shader modules.\n * - Manages geometry attributes and buffer bindings.\n * - Accepts textures, samplers and uniform buffers as bindings, including texture binding sources.\n * - Provides detailed debug logging and optional shader source inspection.\n */\nexport class Model {\n static defaultProps: Required<ModelProps> = {\n ...RenderPipeline.defaultProps,\n source: undefined!,\n vs: null,\n fs: null,\n id: 'unnamed',\n handle: undefined,\n userData: {},\n defines: {},\n modules: [],\n plugins: [],\n geometry: null,\n indexBuffer: null,\n indexCount: undefined!,\n firstVertex: 0,\n firstIndex: 0,\n attributes: {},\n constantAttributes: {},\n bindings: {},\n uniforms: {},\n varyings: [],\n\n isInstanced: undefined!,\n instanceCount: 0,\n vertexCount: 0,\n\n shaderInputs: undefined!,\n material: undefined!,\n pipelineFactory: undefined!,\n shaderFactory: undefined!,\n transformFeedback: undefined!,\n shaderAssembler: ShaderAssembler.getDefaultShaderAssembler(),\n\n debugShaders: undefined!,\n disableWarnings: undefined!\n };\n\n /** Device that created this model */\n readonly device: Device;\n /** Application provided identifier */\n readonly id: string;\n /** WGSL shader source when using unified shader */\n // @ts-expect-error assigned in function called from constructor\n readonly source: string;\n /** GLSL vertex shader source */\n // @ts-expect-error assigned in function called from constructor\n readonly vs: string;\n /** GLSL fragment shader source */\n // @ts-expect-error assigned in function called from constructor\n readonly fs: string;\n /** Factory used to create render pipelines */\n readonly pipelineFactory: PipelineFactory;\n /** Factory used to create shaders */\n readonly shaderFactory: ShaderFactory;\n /** User-supplied per-model data */\n userData: {[key: string]: any} = {};\n\n // Fixed properties (change can trigger pipeline rebuild)\n\n /** The render pipeline GPU parameters, depth testing etc */\n parameters: RenderPipelineParameters;\n\n /** The primitive topology */\n topology: PrimitiveTopology;\n /** Buffer layout */\n bufferLayout: BufferLayout[];\n\n // Dynamic properties\n\n /** Use instanced rendering */\n isInstanced: boolean | undefined = undefined;\n /** instance count. `undefined` means not instanced */\n instanceCount: number = 0;\n /** Vertex count */\n vertexCount: number;\n /** Indexed draw count override. Undefined draws the full bound index buffer. */\n indexCount: number | undefined;\n /** First vertex byte offset for WebGL indexed draws or first vertex for non-indexed draws. */\n firstVertex: number;\n /** First index element for WebGPU indexed draws. */\n firstIndex: number;\n\n /** Index buffer */\n indexBuffer: Buffer | null = null;\n /** Buffer-valued attributes */\n bufferAttributes: Record<string, Buffer> = {};\n /** Constant-valued attributes */\n constantAttributes: Record<string, TypedArray> = {};\n /** Bindings (textures, samplers, uniform buffers) */\n bindings: Record<string, ModelBinding> = {};\n\n /**\n * VertexArray\n * @note not implemented: if bufferLayout is updated, vertex array has to be rebuilt!\n * @todo - allow application to define multiple vertex arrays?\n * */\n vertexArray: VertexArray;\n\n /** TransformFeedback, WebGL 2 only. */\n transformFeedback: TransformFeedback | null = null;\n\n /** The underlying GPU \"program\". @note May be recreated if parameters change */\n pipeline: RenderPipeline;\n\n /** ShaderInputs instance */\n // @ts-expect-error Assigned in function called by constructor\n shaderInputs: ShaderInputs;\n material: Material | null = null;\n // @ts-expect-error Assigned in function called by constructor\n _uniformStore: UniformStore;\n\n _attributeInfos: Record<string, AttributeInfo> = {};\n _gpuGeometry: GPUGeometry | null = null;\n private props: Required<ModelProps>;\n private _dynamicIndexBufferSource: {source: DynamicBuffer; generation: number} | null = null;\n private _dynamicAttributeBufferSources: Record<\n number,\n {source: DynamicBuffer; generation: number}\n > = {};\n private _colorAttachmentFormats: (TextureFormatColor | null)[] | undefined;\n private _depthStencilAttachmentFormat: TextureFormatDepthStencil | undefined;\n\n _pipelineNeedsUpdate: string | false = 'newly created';\n private _needsRedraw: string | false = 'initializing';\n private _drawBlockedReason: string | false = false;\n private _destroyed = false;\n\n /** \"Time\" of last draw. Monotonically increasing timestamp */\n _lastDrawTimestamp: number = -1;\n private _bindingTable: ShaderBindingDebugRow[] = [];\n\n get [Symbol.toStringTag](): string {\n return 'Model';\n }\n\n toString(): string {\n return `Model(${this.id})`;\n }\n\n constructor(device: Device, props: ModelProps) {\n this.props = {...Model.defaultProps, ...props};\n props = this.props;\n this.id = props.id || uid('model');\n this.device = device;\n\n Object.assign(this.userData, props.userData);\n\n this.material = props.material || null;\n\n const platformInfo = getPlatformInfo(device);\n const resolvedPlugins = resolveShaderPlugins(this.props.plugins, platformInfo.shaderLanguage);\n\n // Setup shader module inputs\n const shaderInputModules = mergeShaderPluginModules(\n this.props.modules,\n resolvedPlugins.modules\n );\n const moduleMap = Object.fromEntries(shaderInputModules.map(module => [module.name, module]));\n\n const shaderInputs =\n props.shaderInputs ||\n new ShaderInputs(moduleMap, {disableWarnings: this.props.disableWarnings});\n if (props.shaderInputs && resolvedPlugins.modules.length > 0) {\n shaderInputs.addModules(resolvedPlugins.modules);\n }\n // @ts-ignore\n this.setShaderInputs(shaderInputs);\n\n // Setup shader assembler\n const modules = mergeShaderModules(this.props.modules, shaderInputs.getModules());\n const defines = {...resolvedPlugins.defines, ...this.props.defines};\n\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(this.props.shaderLayout, modules) || null;\n\n const isWebGPU = this.device.type === 'webgpu';\n\n // WebGPU\n // TODO - hack to support unified WGSL shader\n // TODO - this is wrong, compile a single shader\n if (isWebGPU && this.props.source) {\n // WGSL\n const {source, getUniforms, bindingTable} = this.props.shaderAssembler.assembleWGSLShader({\n platformInfo,\n ...this.props,\n modules,\n defines,\n pluginInjections: resolvedPlugins.injections,\n pluginVertexInputs: resolvedPlugins.vertexInputs,\n pluginVaryings: resolvedPlugins.varyings\n });\n this.source = source;\n // @ts-expect-error\n this._getModuleUniforms = getUniforms;\n this._bindingTable = bindingTable;\n // Extract shader layout after modules have been added to WGSL source, to include any bindings added by modules\n const reflectedShaderLayout = (\n device as Device & {getShaderLayout?: (source: string) => any}\n ).getShaderLayout?.(this.source);\n const inferredShaderLayout = normalizeShaderPluginAttributeNames(\n reflectedShaderLayout,\n resolvedPlugins.vertexInputs\n );\n const shaderLayout = mergeInferredShaderLayout(\n this.props.shaderLayout,\n inferredShaderLayout,\n Object.keys(resolvedPlugins.vertexInputs)\n );\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(shaderLayout || null, modules) || null;\n } else {\n // GLSL\n const {vs, fs, getUniforms} = this.props.shaderAssembler.assembleGLSLShaderPair({\n platformInfo,\n ...this.props,\n modules,\n defines,\n pluginInjections: resolvedPlugins.injections,\n pluginVertexInputs: resolvedPlugins.vertexInputs,\n pluginVaryings: resolvedPlugins.varyings\n });\n\n this.vs = vs;\n this.fs = fs;\n // @ts-expect-error\n this._getModuleUniforms = getUniforms;\n this._bindingTable = [];\n }\n\n this.vertexCount = this.props.vertexCount;\n this.indexCount = this.props.indexCount;\n this.firstVertex = this.props.firstVertex;\n this.firstIndex = this.props.firstIndex;\n this.instanceCount = this.props.instanceCount;\n\n this.topology = this.props.topology;\n this.bufferLayout = this.props.bufferLayout;\n this.parameters = this.props.parameters;\n // Seed attachment formats before creating the initial WebGPU pipeline. This is required for\n // depth-only models whose intentional empty color target list must not fall back to the canvas\n // format before the first render pass can synchronize attachment state.\n this._colorAttachmentFormats = this.props.colorAttachmentFormats;\n this._depthStencilAttachmentFormat = this.props.depthStencilAttachmentFormat;\n\n // Geometry, if provided, sets topology and vertex cound\n if (props.geometry) {\n this.setGeometry(props.geometry);\n }\n\n this.pipelineFactory =\n props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);\n this.shaderFactory = props.shaderFactory || ShaderFactory.getDefaultShaderFactory(this.device);\n\n // Create the pipeline\n // @note order is important\n this.pipeline = this._updatePipeline();\n\n this.vertexArray = device.createVertexArray({\n shaderLayout: this.pipeline.shaderLayout,\n bufferLayout: this.pipeline.bufferLayout\n });\n\n // Now we can apply geometry attributes\n if (this._gpuGeometry) {\n this._setGeometryAttributes(this._gpuGeometry);\n }\n\n // Apply any dynamic settings that will not trigger pipeline change\n if ('isInstanced' in props) {\n this.isInstanced = props.isInstanced;\n }\n\n if (props.instanceCount) {\n this.setInstanceCount(props.instanceCount);\n }\n if (props.vertexCount) {\n this.setVertexCount(props.vertexCount);\n }\n if (props.indexBuffer) {\n this.setIndexBuffer(props.indexBuffer);\n }\n if (props.attributes) {\n this.setAttributes(props.attributes);\n }\n if (props.constantAttributes) {\n this.setConstantAttributes(props.constantAttributes);\n }\n if (props.bindings) {\n this.setBindings(props.bindings);\n }\n if (props.transformFeedback) {\n this.transformFeedback = props.transformFeedback;\n }\n }\n\n destroy(): void {\n if (!this._destroyed) {\n // Release pipeline before we destroy the shaders used by the pipeline\n this.pipelineFactory.release(this.pipeline);\n // Release the shaders\n this.shaderFactory.release(this.pipeline.vs);\n if (this.pipeline.fs && this.pipeline.fs !== this.pipeline.vs) {\n this.shaderFactory.release(this.pipeline.fs);\n }\n this._uniformStore.destroy();\n // TODO - mark resource as managed and destroyIfManaged() ?\n this._gpuGeometry?.destroy();\n this._destroyed = true;\n }\n }\n\n // Draw call\n\n /** Query redraw status. Clears the status. */\n needsRedraw(): false | string {\n // Catch any writes to already bound resources\n if (this._getBindingsUpdateTimestamp() > this._lastDrawTimestamp) {\n this.setNeedsRedraw('contents of bound textures or buffers updated');\n }\n const needsRedraw = this._needsRedraw;\n this._needsRedraw = false;\n return needsRedraw;\n }\n\n /** Mark the model as needing a redraw */\n setNeedsRedraw(reason: string): void {\n this._needsRedraw ||= reason;\n }\n\n /** Returns WGSL binding debug rows for the assembled shader. Returns an empty array for GLSL models. */\n getBindingDebugTable(): readonly ShaderBindingDebugRow[] {\n return this._bindingTable;\n }\n\n /**\n * Updates uniforms and pipeline state before opening a render pass.\n *\n * @param commandEncoder - Encoder that should own any GPU uploads emitted\n * during draw preparation.\n */\n predraw(commandEncoder: CommandEncoder): void {\n // Update uniform buffers if needed\n this._syncDynamicBuffers();\n this.updateShaderInputs(commandEncoder);\n this.material?.updateShaderInputs(commandEncoder);\n // Check if the pipeline is invalidated\n this.pipeline = this._updatePipeline();\n }\n\n /**\n * Issue one draw call.\n * @param renderPass - render pass to draw into\n * @returns `true` if the draw call was executed, `false` if resources were not ready.\n */\n draw(renderPass: RenderPass): boolean {\n if (this._drawBlockedReason && !this._pipelineNeedsUpdate) {\n log.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)();\n return false;\n }\n\n const loadingBinding = this._areBindingsLoading();\n if (loadingBinding) {\n log.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${loadingBinding} not loaded`)();\n return false;\n }\n\n this._syncAttachmentFormats(renderPass);\n\n try {\n renderPass.pushDebugGroup(`${this}.predraw(${renderPass})`);\n if (this.device.type === 'webgpu') {\n // WebGPU uploads cannot be encoded once the render pass is already open.\n // Keep the implicit draw() path working for existing callers by falling\n // back to immediate writes here; callers that need upload ordering\n // across multiple draws/viewports must call predraw(commandEncoder)\n // before beginRenderPass().\n this.updateShaderInputs();\n this.material?.updateShaderInputs();\n this._syncDynamicBuffers();\n this.pipeline = this._updatePipeline();\n } else {\n this.predraw(this.device.commandEncoder);\n }\n } finally {\n renderPass.popDebugGroup();\n }\n\n let drawSuccess: boolean;\n let pipelineErrored = this.pipeline.isErrored;\n try {\n renderPass.pushDebugGroup(`${this}.draw(${renderPass})`);\n this._logDrawCallStart();\n\n // Update the pipeline if invalidated\n // TODO - inside RenderPass is likely the worst place to do this from performance perspective.\n // Application can call Model.predraw() to avoid this.\n this.pipeline = this._updatePipeline();\n pipelineErrored = this.pipeline.isErrored;\n\n if (pipelineErrored) {\n log.info(\n LOG_DRAW_PRIORITY,\n `>>> DRAWING ABORTED ${this.id}: ${PIPELINE_INITIALIZATION_FAILED}`\n )();\n drawSuccess = false;\n } else {\n const drawValidationError = this.vertexArray.getDrawValidationError();\n if (drawValidationError) {\n log.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${drawValidationError}`)();\n this._drawBlockedReason = drawValidationError;\n drawSuccess = false;\n } else {\n const shaderLayout = this._getCurrentShaderLayout();\n const syncBindings = this._getBindings(shaderLayout);\n const syncBindGroups = this._getBindGroups(shaderLayout, syncBindings);\n\n const {indexBuffer} = this.vertexArray;\n const indexCount = indexBuffer\n ? (this.indexCount ??\n indexBuffer.byteLength / (indexBuffer.indexType === 'uint32' ? 4 : 2))\n : undefined;\n\n renderPass.setPipeline(this.pipeline);\n renderPass.setBindings(syncBindGroups, {\n _bindGroupCacheKeys: this._getBindGroupCacheKeys()\n });\n renderPass.setVertexArray(this.vertexArray);\n const hasNoInstances = this.isInstanced === true && this.instanceCount === 0;\n drawSuccess = hasNoInstances\n ? true\n : renderPass.draw({\n isInstanced: this.isInstanced,\n vertexCount: this.vertexCount,\n instanceCount: this.isInstanced ? this.instanceCount : undefined,\n indexCount,\n firstVertex: this.firstVertex,\n firstIndex: this.firstIndex,\n transformFeedback: this.transformFeedback || undefined,\n uniforms: this.props.uniforms,\n // WebGL shares underlying cached programs even for models that have different\n // parameters and topology, so those compatibility overrides remain per draw.\n parameters: this.parameters,\n topology: this.topology\n });\n }\n }\n } finally {\n renderPass.popDebugGroup();\n this._logDrawCallEnd();\n }\n this._logFramebuffer(renderPass);\n\n // Update needsRedraw flag\n if (drawSuccess) {\n this._lastDrawTimestamp = this.device.timestamp;\n this._needsRedraw = false;\n } else if (pipelineErrored) {\n this._needsRedraw = PIPELINE_INITIALIZATION_FAILED;\n this._drawBlockedReason = PIPELINE_INITIALIZATION_FAILED;\n } else if (this._drawBlockedReason) {\n this._needsRedraw = this._drawBlockedReason;\n } else {\n this._needsRedraw = 'waiting for resource initialization';\n }\n return drawSuccess;\n }\n\n // Update fixed fields (can trigger pipeline rebuild)\n\n /**\n * Updates the optional geometry\n * Geometry, set topology and bufferLayout\n * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n setGeometry(geometry: GPUGeometry | Geometry | null): void {\n this._gpuGeometry?.destroy();\n const gpuGeometry = geometry && makeGPUGeometry(this.device, geometry);\n if (gpuGeometry) {\n this.setTopology(gpuGeometry.topology || 'triangle-list');\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n this.bufferLayout = bufferLayoutHelper.mergeBufferLayouts(\n gpuGeometry.bufferLayout,\n this.bufferLayout\n );\n if (this.vertexArray) {\n this._setGeometryAttributes(gpuGeometry);\n }\n }\n this._gpuGeometry = gpuGeometry;\n }\n\n /**\n * Updates the primitive topology ('triangle-list', 'triangle-strip' etc).\n * @note Triggers a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n setTopology(topology: PrimitiveTopology): void {\n if (topology !== this.topology) {\n this.topology = topology;\n this._setPipelineNeedsUpdate('topology');\n }\n }\n\n /**\n * Updates the buffer layout.\n * @note Triggers a pipeline rebuild / pipeline cache fetch\n */\n setBufferLayout(bufferLayout: BufferLayout[]): void {\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n const nextBufferLayout = this._gpuGeometry\n ? bufferLayoutHelper.mergeBufferLayouts(bufferLayout, this._gpuGeometry.bufferLayout)\n : bufferLayout;\n if (deepEqual(nextBufferLayout, this.bufferLayout, -1)) {\n return;\n }\n\n this.bufferLayout = nextBufferLayout;\n this._setPipelineNeedsUpdate('bufferLayout');\n\n // Recreate the pipeline\n this.pipeline = this._updatePipeline();\n\n // vertex array needs to be updated if we update buffer layout,\n // but not if we update parameters\n this.vertexArray = this.device.createVertexArray({\n shaderLayout: this.pipeline.shaderLayout,\n bufferLayout: this.pipeline.bufferLayout\n });\n\n // Reapply geometry attributes to the new vertex array\n if (this._gpuGeometry) {\n this._setGeometryAttributes(this._gpuGeometry);\n }\n }\n\n /**\n * Set GPU parameters.\n * @note Can trigger a pipeline rebuild / pipeline cache fetch.\n * @param parameters\n */\n setParameters(parameters: RenderPipelineParameters) {\n if (!deepEqual(parameters, this.parameters, 2)) {\n this.parameters = parameters;\n this._setPipelineNeedsUpdate('parameters');\n }\n }\n\n // Update dynamic fields\n\n /**\n * Updates the instance count (used in draw calls)\n * @note Any attributes with stepMode=instance need to be at least this big\n */\n setInstanceCount(instanceCount: number): void {\n this.instanceCount = instanceCount;\n // luma.gl examples don't set props.isInstanced and rely on auto-detection\n // but deck.gl sets instanceCount even for models that are not instanced.\n if (this.isInstanced === undefined && instanceCount > 0) {\n this.isInstanced = true;\n }\n this.setNeedsRedraw('instanceCount');\n }\n\n /**\n * Updates the vertex count (used in draw calls)\n * @note Any attributes with stepMode=vertex need to be at least this big\n */\n setVertexCount(vertexCount: number): void {\n this.vertexCount = vertexCount;\n this.setNeedsRedraw('vertexCount');\n }\n\n /** Updates the indexed draw count override. */\n setIndexCount(indexCount: number | undefined): void {\n this.indexCount = indexCount;\n this.setNeedsRedraw('indexCount');\n }\n\n /** Updates the first indexed/non-indexed draw offsets. */\n setDrawOffsets({firstVertex, firstIndex}: {firstVertex: number; firstIndex: number}): void {\n this.firstVertex = firstVertex;\n this.firstIndex = firstIndex;\n this.setNeedsRedraw('drawOffsets');\n }\n\n /** Set the shader inputs */\n setShaderInputs(shaderInputs: ShaderInputs): void {\n this.shaderInputs = shaderInputs;\n this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules);\n // Create uniform buffer bindings for all modules that actually have uniforms\n for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) {\n if (shaderModuleHasUniforms(module) && !this.material?.ownsModule(moduleName)) {\n const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName);\n this.bindings[`${moduleName}Uniforms`] = uniformBuffer;\n }\n }\n this.setNeedsRedraw('shaderInputs');\n }\n\n setMaterial(material: Material | null): void {\n this.material = material;\n this.setNeedsRedraw('material');\n }\n\n /** Update uniform buffers from the model's shader inputs */\n /**\n * Flushes current shader-input values into managed uniform buffers and\n * non-material bindings.\n *\n * @param commandEncoder - Optional encoder used to order uniform uploads with\n * subsequent draw commands.\n */\n updateShaderInputs(commandEncoder?: CommandEncoder): void {\n this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(), commandEncoder);\n this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues()));\n // TODO - this is already tracked through buffer/texture update times?\n this.setNeedsRedraw('shaderInputs');\n }\n\n /**\n * Sets bindings (textures, samplers, uniform buffers)\n */\n setBindings(bindings: Record<string, ModelBinding>): void {\n Object.assign(this.bindings, bindings);\n this.setNeedsRedraw('bindings');\n }\n\n /**\n * Updates optional transform feedback. WebGL only.\n */\n setTransformFeedback(transformFeedback: TransformFeedback | null): void {\n this.transformFeedback = transformFeedback;\n this.setNeedsRedraw('transformFeedback');\n }\n\n /**\n * Sets the index buffer\n * @todo - how to unset it if we change geometry?\n */\n setIndexBuffer(indexBuffer: ModelBuffer | null): void {\n const resolvedIndexBuffer =\n indexBuffer instanceof DynamicBuffer ? indexBuffer.buffer : indexBuffer;\n this.indexBuffer = resolvedIndexBuffer;\n this._dynamicIndexBufferSource =\n indexBuffer instanceof DynamicBuffer\n ? {source: indexBuffer, generation: indexBuffer.generation}\n : null;\n this.vertexArray.setIndexBuffer(resolvedIndexBuffer);\n this.setNeedsRedraw('indexBuffer');\n }\n\n /**\n * Sets attributes (buffers)\n * @note Overrides any attributes previously set with the same name\n */\n setAttributes(buffers: Record<string, ModelBuffer>, options?: {disableWarnings?: boolean}): void {\n this._drawBlockedReason = false;\n const disableWarnings = options?.disableWarnings ?? this.props.disableWarnings;\n if (buffers['indices']) {\n log.warn(\n `Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`\n )();\n }\n\n // ensure bufferLayout order matches source layout so we bind\n // the correct buffers to the correct indices in webgpu.\n this.bufferLayout = sortedBufferLayoutByShaderSourceLocations(\n this.pipeline.shaderLayout,\n this.bufferLayout\n );\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n\n // Check if all buffers have a layout\n for (const [bufferName, buffer] of Object.entries(buffers)) {\n const resolvedBuffer = buffer instanceof DynamicBuffer ? buffer.buffer : buffer;\n const bufferLayout = bufferLayoutHelper.getBufferLayout(bufferName);\n if (!bufferLayout) {\n if (!disableWarnings) {\n log.warn(`Model(${this.id}): Missing layout for buffer \"${bufferName}\".`)();\n }\n continue; // eslint-disable-line no-continue\n }\n\n // In WebGL, for an interleaved attribute we may need to set multiple attributes\n // but in WebGPU, we set it according to the buffer's position in the vertexArray\n const attributeNames = bufferLayoutHelper.getAttributeNamesForBuffer(bufferLayout);\n let set = false;\n for (const attributeName of attributeNames) {\n const attributeInfo = this._attributeInfos[attributeName];\n if (attributeInfo) {\n const bufferSlot =\n this.device.type === 'webgpu'\n ? this.vertexArray.getBufferSlot(attributeInfo.bufferName)\n : attributeInfo.location;\n if (bufferSlot === null) {\n if (!disableWarnings) {\n log.warn(\n `Model(${this.id}): Missing vertex array slot for buffer \"${attributeInfo.bufferName}\".`\n )();\n }\n continue; // eslint-disable-line no-continue\n }\n\n this.vertexArray.setBuffer(bufferSlot, resolvedBuffer);\n if (buffer instanceof DynamicBuffer) {\n this._dynamicAttributeBufferSources[bufferSlot] = {\n source: buffer,\n generation: buffer.generation\n };\n } else {\n delete this._dynamicAttributeBufferSources[bufferSlot];\n }\n set = true;\n }\n }\n if (!set && !disableWarnings) {\n log.warn(\n `Model(${this.id}): Ignoring buffer \"${resolvedBuffer.id}\" for unknown attribute \"${bufferName}\"`\n )();\n }\n }\n this.setNeedsRedraw('attributes');\n }\n\n /**\n * Sets constant attributes\n * @note Overrides any attributes previously set with the same name\n * Constant attributes are only supported in WebGL, not in WebGPU\n * Any attribute that is disabled in the current vertex array object\n * is read from the context's global constant value for that attribute location.\n * @param constantAttributes\n */\n setConstantAttributes(\n attributes: Record<string, TypedArray>,\n options?: {disableWarnings?: boolean}\n ): void {\n for (const [attributeName, value] of Object.entries(attributes)) {\n const attributeInfo = this._attributeInfos[attributeName];\n if (attributeInfo) {\n this.vertexArray.setConstantWebGL(attributeInfo.location, value);\n } else if (!(options?.disableWarnings ?? this.props.disableWarnings)) {\n log.warn(\n `Model \"${this.id}: Ignoring constant supplied for unknown attribute \"${attributeName}\"`\n )();\n }\n }\n this.setNeedsRedraw('constants');\n }\n\n // INTERNAL METHODS\n\n /** Check that bindings are loaded. Returns id of first binding that is still loading. */\n _areBindingsLoading(): string | false {\n for (const binding of Object.values(this.bindings)) {\n if (isTextureBindingSource(binding) && !binding.isReady) {\n return binding.id;\n }\n }\n for (const binding of Object.values(this.material?.bindings || {})) {\n if (isTextureBindingSource(binding) && !binding.isReady) {\n return binding.id;\n }\n }\n return false;\n }\n\n /**\n * Resolves ready model bindings for the current shader layout.\n * @param shaderLayout Reflected bindings used to select copied or external texture resolution.\n */\n _getBindings(\n shaderLayout: AnyShaderLayout = this._getCurrentShaderLayout()\n ): Record<string, Binding> {\n const validBindings: Record<string, Binding> = {};\n\n for (const [name, binding] of Object.entries(this.bindings)) {\n const resolvedBinding = resolveModelBinding(name, binding, shaderLayout);\n if (resolvedBinding) {\n validBindings[name] = resolvedBinding;\n }\n }\n\n return validBindings;\n }\n\n /**\n * Groups resolved model and material bindings for the current shader layout.\n * @param shaderLayout Reflected bindings used to group logical binding names.\n * @param bindings Model bindings already resolved for this draw preparation.\n */\n _getBindGroups(\n shaderLayout: AnyShaderLayout = this._getCurrentShaderLayout(),\n bindings: Record<string, Binding> = this._getBindings(shaderLayout)\n ): BindingsByGroup {\n const bindGroups = shaderLayout.bindings.length\n ? normalizeBindingsByGroup(shaderLayout, bindings)\n : {0: bindings};\n\n if (!this.material) {\n return bindGroups;\n }\n\n for (const [groupKey, groupBindings] of Object.entries(\n this.material.getBindingsByGroup(shaderLayout)\n )) {\n const group = Number(groupKey);\n bindGroups[group] = {\n ...(bindGroups[group] || {}),\n ...groupBindings\n };\n }\n\n return bindGroups;\n }\n\n _getBindGroupCacheKeys(): Partial<Record<number, object>> {\n const bindGroupCacheKey = this.material?.getBindGroupCacheKey(3);\n return bindGroupCacheKey ? {3: bindGroupCacheKey} : {};\n }\n\n /** Get the timestamp of the latest updated bound GPU memory resource (buffer/texture). */\n _getBindingsUpdateTimestamp(): number {\n let timestamp = 0;\n if (this._dynamicIndexBufferSource) {\n timestamp = Math.max(timestamp, this._dynamicIndexBufferSource.source.updateTimestamp);\n }\n for (const entry of Object.values(this._dynamicAttributeBufferSources)) {\n timestamp = Math.max(timestamp, entry.source.updateTimestamp);\n }\n for (const binding of Object.values(this.bindings)) {\n if (binding instanceof TextureView) {\n timestamp = Math.max(timestamp, binding.texture.updateTimestamp);\n } else if (\n binding instanceof Buffer ||\n binding instanceof Texture ||\n binding instanceof ExternalTexture\n ) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (binding instanceof DynamicBuffer) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (isTextureBindingSource(binding)) {\n timestamp = binding.isReady\n ? Math.max(timestamp, binding.updateTimestamp)\n : // The texture will become available in the future\n Infinity;\n } else if (isBufferRangeBinding(binding)) {\n timestamp = Math.max(\n timestamp,\n binding.buffer instanceof DynamicBuffer\n ? binding.buffer.updateTimestamp\n : binding.buffer.updateTimestamp\n );\n }\n }\n return Math.max(timestamp, this.material?.getBindingsUpdateTimestamp() || 0);\n }\n\n /**\n * Updates the optional geometry attributes\n * Geometry, sets several attributes, indexBuffer, and also vertex count\n * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n _setGeometryAttributes(gpuGeometry: GPUGeometry): void {\n // Filter geometry attribute so that we don't issue warnings for unused attributes\n const attributes = {...gpuGeometry.attributes};\n for (const [attributeName] of Object.entries(attributes)) {\n if (\n !this.pipeline.shaderLayout.attributes.find(layout => layout.name === attributeName) &&\n attributeName !== 'positions'\n ) {\n delete attributes[attributeName];\n }\n }\n\n // TODO - delete previous geometry?\n this.vertexCount = gpuGeometry.vertexCount;\n this.setIndexBuffer(gpuGeometry.indices || null);\n this.setAttributes(gpuGeometry.attributes, {disableWarnings: true});\n this.setAttributes(attributes, {disableWarnings: this.props.disableWarnings});\n\n this.setNeedsRedraw('geometry attributes');\n }\n\n /** Mark pipeline as needing update */\n _setPipelineNeedsUpdate(reason: string): void {\n this._pipelineNeedsUpdate ||= reason;\n this._drawBlockedReason = false;\n this.setNeedsRedraw(reason);\n }\n\n /** Update pipeline if needed */\n _updatePipeline(): RenderPipeline {\n if (this._pipelineNeedsUpdate) {\n let prevShaderVs: Shader | null = null;\n let prevShaderFs: Shader | null = null;\n if (this.pipeline) {\n log.log(\n 1,\n `Model ${this.id}: Recreating pipeline because \"${this._pipelineNeedsUpdate}\".`\n )();\n prevShaderVs = this.pipeline.vs;\n prevShaderFs = this.pipeline.fs;\n }\n\n this._pipelineNeedsUpdate = false;\n\n const vs = this.shaderFactory.createShader({\n id: `${this.id}-vertex`,\n stage: 'vertex',\n source: this.source || this.vs,\n debugShaders: this.props.debugShaders\n });\n\n let fs: Shader | null = null;\n if (this.source) {\n fs = vs;\n } else if (this.fs) {\n fs = this.shaderFactory.createShader({\n id: `${this.id}-fragment`,\n stage: 'fragment',\n source: this.source || this.fs,\n debugShaders: this.props.debugShaders\n });\n }\n\n this.pipeline = this.pipelineFactory.createRenderPipeline({\n ...this.props,\n bindings: undefined,\n bufferLayout: this.bufferLayout,\n colorAttachmentFormats: this._colorAttachmentFormats,\n depthStencilAttachmentFormat: this._depthStencilAttachmentFormat,\n topology: this.topology,\n parameters: this.parameters,\n bindGroups: undefined,\n vs,\n fs\n });\n\n this._attributeInfos = getAttributeInfosFromLayouts(\n this.pipeline.shaderLayout,\n this.bufferLayout\n );\n\n if (prevShaderVs) this.shaderFactory.release(prevShaderVs);\n if (prevShaderFs && prevShaderFs !== prevShaderVs) {\n this.shaderFactory.release(prevShaderFs);\n }\n }\n return this.pipeline;\n }\n\n /** Throttle draw call logging */\n _lastLogTime = 0;\n _logOpen = false;\n\n _logDrawCallStart(): void {\n // IF level is 4 or higher, log every frame.\n const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;\n if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {\n return;\n }\n\n this._lastLogTime = Date.now();\n this._logOpen = true;\n\n log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {collapsed: log.level <= 2})();\n }\n\n _logDrawCallEnd(): void {\n if (this._logOpen) {\n const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.shaderLayout, this.id);\n\n // log.table(logLevel, attributeTable)();\n // log.table(logLevel, uniformTable)();\n log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();\n\n const uniformTable = this.shaderInputs.getDebugTable();\n log.table(LOG_DRAW_PRIORITY, uniformTable)();\n\n const attributeTable = this._getAttributeDebugTable();\n log.table(LOG_DRAW_PRIORITY, this._attributeInfos)();\n log.table(LOG_DRAW_PRIORITY, attributeTable)();\n\n log.groupEnd(LOG_DRAW_PRIORITY)();\n this._logOpen = false;\n }\n }\n\n protected _drawCount = 0;\n _logFramebuffer(renderPass: RenderPass): void {\n const debugFramebuffers = this.device.props.debugFramebuffers;\n this._drawCount++;\n // Update first 3 frames and then every 60 frames\n if (!debugFramebuffers) {\n // } || (this._drawCount++ > 3 && this._drawCount % 60)) {\n return;\n }\n const framebuffer = renderPass.props.framebuffer;\n debugFramebuffer(renderPass, framebuffer, {\n id: framebuffer?.id || `${this.id}-framebuffer`,\n minimap: true\n });\n }\n\n _getAttributeDebugTable(): Record<string, Record<string, unknown>> {\n const table: Record<string, Record<string, unknown>> = {};\n for (const [name, attributeInfo] of Object.entries(this._attributeInfos)) {\n const values = this.vertexArray.attributes[attributeInfo.location];\n table[attributeInfo.location] = {\n name,\n type: attributeInfo.shaderType,\n values: values\n ? this._getBufferOrConstantValues(values, attributeInfo.bufferDataType)\n : 'null'\n };\n }\n if (this.vertexArray.indexBuffer) {\n const {indexBuffer} = this.vertexArray;\n const values =\n indexBuffer.indexType === 'uint32'\n ? new Uint32Array(indexBuffer.debugData)\n : new Uint16Array(indexBuffer.debugData);\n table['indices'] = {\n name: 'indices',\n type: indexBuffer.indexType,\n values: values.toString()\n };\n }\n return table;\n }\n\n // TODO - fix typing of luma data types\n _getBufferOrConstantValues(attribute: Buffer | TypedArray, dataType: any): string {\n const TypedArrayConstructor = dataTypeDecoder.getTypedArrayConstructor(dataType);\n const typedArray =\n attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;\n return typedArray.toString();\n }\n\n private _getNonMaterialBindings(\n bindings: Record<string, ModelBinding>\n ): Record<string, ModelBinding> {\n if (!this.material) {\n return bindings;\n }\n\n const filteredBindings: Record<string, ModelBinding> = {};\n for (const [name, binding] of Object.entries(bindings)) {\n if (!this.material.ownsBinding(name)) {\n filteredBindings[name] = binding;\n }\n }\n return filteredBindings;\n }\n\n /** Returns the current reflected shader layout or the pre-reflection empty layout. */\n private _getCurrentShaderLayout(): AnyShaderLayout {\n return this.pipeline?.shaderLayout || this.props.shaderLayout || {bindings: []};\n }\n\n private _syncDynamicBuffers(): void {\n if (\n this._dynamicIndexBufferSource &&\n this._dynamicIndexBufferSource.generation !== this._dynamicIndexBufferSource.source.generation\n ) {\n const resolvedIndexBuffer = this._dynamicIndexBufferSource.source.buffer;\n this.indexBuffer = resolvedIndexBuffer;\n this.vertexArray.setIndexBuffer(resolvedIndexBuffer);\n this._dynamicIndexBufferSource.generation = this._dynamicIndexBufferSource.source.generation;\n this.setNeedsRedraw('dynamic index buffer');\n }\n\n for (const [locationKey, entry] of Object.entries(this._dynamicAttributeBufferSources)) {\n if (entry.generation !== entry.source.generation) {\n this.vertexArray.setBuffer(Number(locationKey), entry.source.buffer);\n entry.generation = entry.source.generation;\n this.setNeedsRedraw('dynamic attribute buffer');\n }\n }\n }\n private _syncAttachmentFormats(renderPass: RenderPass): void {\n if (this.device.type !== 'webgpu') {\n return;\n }\n\n const framebuffer =\n (\n renderPass as RenderPass & {\n framebuffer?: {\n colorAttachments?: Array<{texture?: {format?: TextureFormatColor}} | null>;\n depthStencilAttachment?: {texture?: {format?: TextureFormatDepthStencil}} | null;\n };\n }\n ).framebuffer || renderPass.props.framebuffer;\n const renderBundleProps = renderPass.props as RenderPass['props'] & {\n colorAttachmentFormats?: (TextureFormatColor | null)[];\n depthStencilAttachmentFormat?: TextureFormatDepthStencil | false;\n };\n\n const nextColorAttachmentFormats =\n renderBundleProps.colorAttachmentFormats ??\n framebuffer?.colorAttachments?.map(colorAttachment =>\n asColorAttachmentFormat(colorAttachment?.texture?.format)\n );\n const nextDepthStencilAttachmentFormat =\n renderBundleProps.depthStencilAttachmentFormat === false\n ? undefined\n : (renderBundleProps.depthStencilAttachmentFormat ??\n asDepthStencilAttachmentFormat(framebuffer?.depthStencilAttachment?.texture?.format));\n\n if (\n !deepEqual(this._colorAttachmentFormats, nextColorAttachmentFormats, 1) ||\n this._depthStencilAttachmentFormat !== nextDepthStencilAttachmentFormat\n ) {\n this._colorAttachmentFormats = nextColorAttachmentFormats;\n this._depthStencilAttachmentFormat = nextDepthStencilAttachmentFormat;\n this._setPipelineNeedsUpdate('attachment formats');\n }\n }\n}\n\n// HELPERS\n\nfunction normalizeShaderPluginAttributeNames(\n shaderLayout: ShaderLayout | null | undefined,\n vertexInputs: Record<string, AttributeShaderType>\n): ShaderLayout | null | undefined {\n if (!shaderLayout || Object.keys(vertexInputs).length === 0) {\n return shaderLayout;\n }\n\n return {\n ...shaderLayout,\n attributes: shaderLayout.attributes.map(attribute => {\n const publicName = attribute.name.startsWith('_luma_')\n ? attribute.name.slice('_luma_'.length)\n : null;\n return publicName && vertexInputs[publicName] ? {...attribute, name: publicName} : attribute;\n })\n };\n}\n\n/**\n * Resolves one model binding against the current shader layout.\n * @param bindingName Logical model binding name.\n * @param binding Model binding or deferred engine binding source.\n * @param shaderLayout Reflected bindings used to select copied or external texture resolution.\n * @returns Concrete core binding, or `null` while a deferred source is unavailable.\n */\nfunction resolveModelBinding(\n bindingName: string,\n binding: ModelBinding,\n shaderLayout: AnyShaderLayout\n): Binding | null {\n if (isTextureBindingSource(binding)) {\n const bindingLayout = getTextureBindingLayout(shaderLayout, bindingName, {\n fallbackGroup: 0\n });\n return bindingLayout ? binding.resolveTextureBinding(bindingLayout) : null;\n }\n\n if (binding instanceof DynamicBuffer) {\n return binding.buffer;\n }\n\n if (isBufferRangeBinding(binding)) {\n return resolveBufferRangeBinding(binding);\n }\n\n return binding;\n}\nfunction asColorAttachmentFormat(format?: string | null): TextureFormatColor | null {\n return format && !isDepthStencilAttachmentFormat(format) ? (format as TextureFormatColor) : null;\n}\n\nfunction asDepthStencilAttachmentFormat(\n format?: string | null\n): TextureFormatDepthStencil | undefined {\n return format && isDepthStencilAttachmentFormat(format) ? format : undefined;\n}\n\nfunction isDepthStencilAttachmentFormat(format: string): format is TextureFormatDepthStencil {\n return DEPTH_STENCIL_ATTACHMENT_FORMATS.includes(format as TextureFormatDepthStencil);\n}\n\n/** Create a shadertools platform info from the Device */\nexport function getPlatformInfo(device: Device): PlatformInfo {\n return {\n type: device.type,\n shaderLanguage: device.info.shadingLanguage,\n shaderLanguageVersion: device.info.shadingLanguageVersion as 100 | 300,\n gpu: device.info.gpu,\n limits: device.limits as unknown as Record<string, number | undefined>,\n // HACK - we pretend that the DeviceFeatures is a Set, it has a similar API\n features: device.features as unknown as Set<DeviceFeature>\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PrimitiveTopology, BufferLayout} from '@luma.gl/core';\nimport {Device, Buffer} from '@luma.gl/core';\nimport {type Geometry, getGeometryShaderAttributeName} from '../geometry/geometry';\nimport {makeInterleavedGeometry} from './geometry-utils';\nimport {uid} from '../utils/uid';\n\n/** Properties used to create a {@link GPUGeometry}. */\nexport type GPUGeometryProps = {\n /** Application-provided identifier. */\n id?: string;\n\n /** Determines how vertices are assembled into primitives. */\n topology: 'point-list' | 'line-list' | 'line-strip' | 'triangle-list' | 'triangle-strip';\n\n /** Draw vertex count. */\n vertexCount: number;\n\n /** Buffer layout matching the supplied GPU vertex buffers. */\n bufferLayout: BufferLayout[];\n\n /** Optional GPU index buffer. */\n indices?: Buffer | null;\n\n /** GPU vertex buffers, keyed by buffer layout name. */\n attributes: Record<string, Buffer>;\n};\n\n/**\n * GPU-backed geometry container.\n *\n * `GPUGeometry` owns already-created vertex and index buffers plus the `bufferLayout` metadata\n * needed to bind those buffers to shader attributes.\n */\nexport class GPUGeometry {\n /** Application-provided or generated identifier. */\n readonly id: string;\n\n /** Application-owned metadata. */\n userData: Record<string, unknown> = {};\n\n /** Determines how vertices are assembled into primitives. */\n readonly topology?: PrimitiveTopology;\n\n /** Buffer layout matching {@link GPUGeometry.attributes}. */\n readonly bufferLayout: BufferLayout[] = [];\n\n /** Resolved draw vertex count. */\n readonly vertexCount: number;\n\n /** Optional GPU index buffer. */\n readonly indices?: Buffer | null;\n\n /** GPU vertex buffers, keyed by buffer layout name. */\n readonly attributes: Record<string, Buffer>;\n\n /** Creates GPU-backed geometry from existing buffers. */\n constructor(props: GPUGeometryProps) {\n this.id = props.id || uid('geometry');\n this.topology = props.topology;\n this.indices = props.indices || null;\n this.attributes = props.attributes;\n\n this.vertexCount = props.vertexCount;\n\n this.bufferLayout = props.bufferLayout || [];\n\n if (this.indices) {\n if (!(this.indices.usage & Buffer.INDEX)) {\n throw new Error('Index buffer must have INDEX usage');\n }\n }\n }\n\n /** Destroys the owned index and vertex buffers. */\n destroy(): void {\n this.indices?.destroy();\n for (const attribute of Object.values(this.attributes)) {\n attribute.destroy();\n }\n }\n\n /** Returns the draw vertex count. */\n getVertexCount(): number {\n return this.vertexCount;\n }\n\n /** Returns the GPU vertex buffers. */\n getAttributes(): Record<string, Buffer> {\n return this.attributes;\n }\n\n /** Returns the GPU index buffer, or `null` for non-indexed geometry. */\n getIndexes(): Buffer | null {\n return this.indices || null;\n }\n\n _calculateVertexCount(positions: Buffer): number {\n // Assume that positions is a fully packed float32x3 buffer\n const vertexCount = positions.byteLength / 12;\n return vertexCount;\n }\n}\n\n/**\n * Converts CPU geometry into GPU geometry.\n *\n * CPU `Geometry` input is interleaved before upload so the resulting `GPUGeometry` has one vertex\n * buffer plus an optional index buffer. Passing a `GPUGeometry` returns the original instance.\n */\nexport function makeGPUGeometry(device: Device, geometry: Geometry | GPUGeometry): GPUGeometry {\n if (geometry instanceof GPUGeometry) {\n return geometry;\n }\n\n const sourceGeometry = makeInterleavedGeometry(geometry);\n const indices = getIndexBufferFromGeometry(device, sourceGeometry);\n const {attributes, bufferLayout} = getAttributeBuffersFromGeometry(device, sourceGeometry);\n return new GPUGeometry({\n topology: sourceGeometry.topology || 'triangle-list',\n bufferLayout,\n vertexCount: sourceGeometry.vertexCount,\n indices,\n attributes\n });\n}\n\n/** Creates a GPU index buffer from CPU geometry index data, when present. */\nexport function getIndexBufferFromGeometry(device: Device, geometry: Geometry): Buffer | undefined {\n if (!geometry.indices) {\n return undefined;\n }\n const data = geometry.indices.value;\n return device.createBuffer({usage: Buffer.INDEX, data});\n}\n\n/**\n * Uploads one GPU vertex buffer for each CPU geometry attribute key and preserves its buffer\n * layout metadata.\n */\nexport function getAttributeBuffersFromGeometry(\n device: Device,\n geometry: Geometry\n): {attributes: Record<string, Buffer>; bufferLayout: BufferLayout[]; vertexCount: number} {\n const attributes: Record<string, Buffer> = {};\n for (const [attributeName, attribute] of Object.entries(geometry.attributes)) {\n const name =\n geometry.bufferLayout.find(bufferLayout => bufferLayout.name === attributeName)?.name ||\n getGeometryShaderAttributeName(attributeName);\n if (attribute) {\n attributes[name] = device.createBuffer({\n data: attribute.value,\n id: `${attributeName}-buffer`\n });\n }\n }\n\n return {\n attributes,\n bufferLayout: geometry.bufferLayout,\n vertexCount: geometry.vertexCount\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '@math.gl/core';\nimport type {BufferLayout, PrimitiveTopology} from '@luma.gl/core';\nimport {vertexFormatDecoder} from '@luma.gl/core';\nimport {uid} from '../utils/uid';\n\n/** CPU-side attribute data accepted by {@link Geometry}. */\nexport type GeometryAttributeInput = GeometryAttribute | TypedArray;\n\n/** Properties used to create a {@link Geometry}. */\nexport type GeometryProps = {\n /** Application-provided identifier. */\n id?: string;\n /** Determines how vertices are assembled into primitives. */\n topology: 'point-list' | 'line-list' | 'line-strip' | 'triangle-list' | 'triangle-strip';\n /** Draw vertex count. Auto-calculated from attributes or indices when omitted. */\n vertexCount?: number;\n /** CPU attributes, keyed by caller-provided names such as glTF mesh attribute semantics. */\n attributes: Record<string, GeometryAttributeInput>;\n /**\n * Maps geometry buffers to shader attributes.\n *\n * If omitted, the constructor creates one shader-facing buffer layout entry for each attribute.\n * Explicit buffer layouts are preserved unchanged.\n */\n bufferLayout?: BufferLayout[];\n /** Optional index data. Indices are always stored separately from vertex attributes. */\n indices?: GeometryAttribute | TypedArray;\n};\n\n/** Attributes returned by {@link Geometry.getAttributes}. */\nexport type GeometryAttributes = Record<string, GeometryAttribute | undefined> & {\n /** Optional index attribute, included when the geometry is indexed. */\n indices?: GeometryAttribute & {size: 1; value: Uint32Array | Uint16Array};\n};\n\n/** Typed-array backed CPU geometry attribute. */\nexport type GeometryAttribute = {\n /** Number of typed-array elements per vertex. */\n size?: number;\n /** Attribute data. */\n value: TypedArray;\n /** Additional attribute metadata consumed by geometry utilities. */\n [key: string]: any;\n};\n\n/**\n * CPU-side geometry container.\n *\n * `Geometry` stores typed-array vertex data, optional index data, and an always-populated\n * `bufferLayout` that describes how its attributes map to shader inputs. CPU attribute names are\n * preserved as supplied; synthesized buffer layouts map supported glTF-style names such as\n * `POSITION` and `TEXCOORD_0` to default shader names such as `positions` and `texCoords`.\n */\nexport class Geometry {\n /** Application-provided or generated identifier. */\n readonly id: string;\n\n /** Determines how vertices are assembled into primitives. */\n readonly topology?: PrimitiveTopology;\n\n /** Resolved draw vertex count. */\n readonly vertexCount: number;\n\n /** Optional index attribute. */\n readonly indices?: GeometryAttribute;\n\n /** CPU attributes, keyed by caller-provided source attribute name. */\n readonly attributes: Record<string, GeometryAttribute | undefined>;\n\n /** Buffer layout matching the geometry attributes. Always populated. */\n readonly bufferLayout: BufferLayout[];\n\n /** Application-owned metadata. */\n userData: Record<string, unknown> = {};\n\n /** Creates a CPU geometry and wraps raw typed arrays into attribute records. */\n constructor(props: GeometryProps) {\n const {attributes = {}, indices = null, vertexCount = null} = props;\n\n this.id = props.id || uid('geometry');\n this.topology = props.topology;\n\n if (indices) {\n this.indices = ArrayBuffer.isView(indices) ? {value: indices, size: 1} : indices;\n }\n\n this.attributes = {};\n\n for (const [attributeName, attributeValue] of Object.entries(attributes)) {\n // Wrap \"unwrapped\" arrays and try to autodetect their type\n const attribute: GeometryAttribute = ArrayBuffer.isView(attributeValue)\n ? {value: attributeValue}\n : attributeValue;\n\n if (!ArrayBuffer.isView(attribute.value)) {\n throw new Error(\n `${this._print(attributeName)}: must be typed array or object with value as typed array`\n );\n }\n\n if ((attributeName === 'POSITION' || attributeName === 'positions') && !attribute.size) {\n attribute.size = 3;\n }\n\n // Move indices to separate field\n if (attributeName === 'indices') {\n if (this.indices) {\n throw new Error('Multiple indices detected');\n }\n this.indices = attribute;\n } else {\n const shaderAttributeName = getGeometryShaderAttributeName(attributeName);\n const storedAttributeName = Object.keys(this.attributes).find(\n name => getGeometryShaderAttributeName(name) === shaderAttributeName\n );\n if (storedAttributeName) {\n delete this.attributes[storedAttributeName];\n }\n this.attributes[attributeName] = attribute;\n }\n }\n\n if (this.indices && this.indices['isIndexed'] !== undefined) {\n this.indices = Object.assign({}, this.indices);\n delete this.indices['isIndexed'];\n }\n\n this.vertexCount = vertexCount || this._calculateVertexCount(this.attributes, this.indices);\n this.bufferLayout =\n props.bufferLayout || getBufferLayoutFromGeometryAttributes(this.attributes);\n }\n\n /** Returns the resolved draw vertex count. */\n getVertexCount(): number {\n return this.vertexCount;\n }\n\n /** Returns all attributes, including `indices` when index data is present. */\n getAttributes(): GeometryAttributes {\n return (\n this.indices ? {indices: this.indices, ...this.attributes} : this.attributes\n ) as GeometryAttributes;\n }\n\n // PRIVATE\n\n _print(attributeName: string): string {\n return `Geometry ${this.id} attribute ${attributeName}`;\n }\n\n _setAttributes(attributes: Record<string, GeometryAttribute>, indices: any): this {\n return this;\n }\n\n _calculateVertexCount(\n attributes: Record<string, GeometryAttribute | undefined>,\n indices?: GeometryAttribute\n ): number {\n if (indices) {\n return indices.value.length;\n }\n let vertexCount = Infinity;\n for (const attribute of Object.values(attributes)) {\n if (!attribute) {\n continue; // eslint-disable-line no-continue\n }\n const {value, size, constant} = attribute;\n if (!constant && value && size !== undefined && size >= 1) {\n vertexCount = Math.min(vertexCount, value.length / size);\n }\n }\n\n // assert(Number.isFinite(vertexCount));\n return vertexCount;\n }\n}\n\n/**\n * Converts supported geometry semantic names to default shader attribute names.\n *\n * Use this only at render-layout boundaries. CPU `Geometry.attributes` preserves source names.\n * Names that do not have a built-in mapping are returned unchanged.\n */\nexport function getGeometryShaderAttributeName(attributeName: string): string {\n switch (attributeName) {\n case 'POSITION':\n return 'positions';\n case 'NORMAL':\n return 'normals';\n case 'TEXCOORD_0':\n return 'texCoords';\n case 'TEXCOORD_1':\n return 'texCoords1';\n case 'COLOR_0':\n return 'colors';\n default:\n return attributeName;\n }\n}\n\nfunction getBufferLayoutFromGeometryAttributes(\n attributes: Record<string, GeometryAttribute | undefined>\n): BufferLayout[] {\n const bufferLayout: BufferLayout[] = [];\n for (const [attributeName, attribute] of Object.entries(attributes)) {\n if (!attribute) {\n continue; // eslint-disable-line no-continue\n }\n const {value, size, normalized} = attribute;\n if (size === undefined) {\n throw new Error(`Attribute ${attributeName} is missing a size`);\n }\n bufferLayout.push({\n name: getGeometryShaderAttributeName(attributeName),\n format: vertexFormatDecoder.getVertexFormatFromAttribute(value, size, normalized)\n });\n }\n return bufferLayout;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record<string, number> = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {VertexFormat} from '@luma.gl/core';\nimport {vertexFormatDecoder} from '@luma.gl/core';\nimport type {TypedArray} from '@math.gl/core';\nimport {Geometry, getGeometryShaderAttributeName, type GeometryAttribute} from './geometry';\n\ntype TypedArrayConstructor = {\n new (length: number): TypedArray;\n new (buffer: ArrayBufferLike): TypedArray;\n readonly BYTES_PER_ELEMENT: number;\n};\n\ntype GeometryLike = {\n indices?: GeometryAttribute;\n attributes: Record<string, GeometryAttribute | undefined>;\n};\n\n/** Options for {@link makeInterleavedGeometry}. */\nexport type MakeInterleavedGeometryOptions = {\n /** Name of the packed geometry buffer. Defaults to `geometry`. */\n bufferName?: string;\n\n /** Attribute names to pack. Defaults to all non-index geometry attributes. */\n attributes?: string[];\n\n /**\n * Minimum byte alignment for each packed attribute and for the final byte stride.\n *\n * Defaults to 4 bytes, matching WebGPU and WebGL vertex-buffer alignment constraints.\n */\n minAttributeAlignment?: number;\n};\n\ntype InterleavedAttribute = {\n sourceName: string;\n attributeName: string;\n value: TypedArray;\n size: number;\n format: VertexFormat;\n byteOffset: number;\n byteLength: number;\n};\n\n/**\n * Expands indexed geometry attributes into non-indexed attributes.\n *\n * The returned object keeps the original attribute keys and replaces each non-constant attribute\n * with data expanded through the index buffer. The `indices` field is intentionally omitted from\n * the returned geometry-like object.\n */\nexport function unpackIndexedGeometry<T extends GeometryLike>(geometry: T): GeometryLike {\n const {indices, attributes} = geometry;\n if (!indices) {\n return geometry;\n }\n\n const vertexCount = indices.value.length;\n const unpackedAttributes: Record<string, GeometryAttribute> = {};\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n if (!attribute) {\n continue; // eslint-disable-line\n }\n const {value, size} = attribute;\n const constant = attribute['constant'];\n if (constant || !size) {\n continue; // eslint-disable-line\n }\n const ArrayType = value.constructor as TypedArrayConstructor;\n const unpackedValue = new ArrayType(vertexCount * size);\n for (let x = 0; x < vertexCount; ++x) {\n const index = indices.value[x];\n for (let i = 0; i < size; i++) {\n unpackedValue[x * size + i] = value[index * size + i];\n }\n }\n unpackedAttributes[attributeName] = {size, value: unpackedValue};\n }\n\n return {\n attributes: Object.assign({}, attributes, unpackedAttributes)\n };\n}\n\n/**\n * Packs a CPU {@link Geometry} into one interleaved vertex buffer.\n *\n * The returned value is a normal `Geometry` whose `attributes` contains one packed typed array,\n * and whose `bufferLayout` maps that packed buffer back to the original shader attributes.\n * Calling this function on an already interleaved geometry with the same `bufferName` is\n * idempotent and returns the original instance.\n */\nexport function makeInterleavedGeometry(\n geometry: Geometry,\n options: MakeInterleavedGeometryOptions = {}\n): Geometry {\n const bufferName = options.bufferName || 'geometry';\n if (isInterleavedGeometry(geometry, bufferName)) {\n return geometry;\n }\n\n const minAttributeAlignment = options.minAttributeAlignment || 4;\n const sourceAttributes = getInterleavedSourceAttributes(geometry, options.attributes);\n const interleavedAttributes: InterleavedAttribute[] = [];\n let byteOffset = 0;\n let attributeVertexCount = Infinity;\n\n for (const [sourceName, attribute] of sourceAttributes) {\n if (!attribute) {\n continue; // eslint-disable-line no-continue\n }\n if (attribute['constant']) {\n throw new Error(`Attribute ${sourceName} is constant`);\n }\n const {value, size, normalized} = attribute;\n if (!ArrayBuffer.isView(value)) {\n throw new Error(`Attribute ${sourceName} is missing typed array data`);\n }\n if (size === undefined) {\n throw new Error(`Attribute ${sourceName} is missing a size`);\n }\n\n const format = vertexFormatDecoder.getVertexFormatFromAttribute(value, size, normalized);\n const vertexFormatInfo = vertexFormatDecoder.getVertexFormatInfo(format);\n\n byteOffset = alignTo(byteOffset, minAttributeAlignment);\n interleavedAttributes.push({\n sourceName,\n attributeName: getGeometryShaderAttributeName(sourceName),\n value,\n size,\n format,\n byteOffset,\n byteLength: vertexFormatInfo.byteLength\n });\n byteOffset += vertexFormatInfo.byteLength;\n const sourceVertexCount = value.length / size;\n if (!Number.isInteger(sourceVertexCount)) {\n throw new Error(`Attribute ${sourceName} length is not divisible by size`);\n }\n attributeVertexCount = Math.min(attributeVertexCount, sourceVertexCount);\n }\n\n if (interleavedAttributes.length === 0 || !Number.isFinite(attributeVertexCount)) {\n throw new Error(`Geometry ${geometry.id} has no interleavable attributes`);\n }\n\n const byteStride = alignTo(byteOffset, minAttributeAlignment);\n const arrayBuffer = new ArrayBuffer(attributeVertexCount * byteStride);\n\n for (const attribute of interleavedAttributes) {\n writeInterleavedAttribute(arrayBuffer, attributeVertexCount, byteStride, attribute);\n }\n\n return new Geometry({\n id: geometry.id,\n topology: geometry.topology || 'triangle-list',\n vertexCount: geometry.vertexCount,\n indices: geometry.indices,\n attributes: {\n [bufferName]: {\n value: new Uint8Array(arrayBuffer),\n size: byteStride,\n byteStride\n }\n },\n bufferLayout: [\n {\n name: bufferName,\n stepMode: 'vertex',\n byteStride,\n attributes: interleavedAttributes.map(attribute => ({\n attribute: attribute.attributeName,\n format: attribute.format,\n byteOffset: attribute.byteOffset\n }))\n }\n ]\n });\n}\n\nfunction isInterleavedGeometry(geometry: Geometry, bufferName: string): boolean {\n if (geometry.bufferLayout.length !== 1) {\n return false;\n }\n\n const bufferLayout = geometry.bufferLayout[0];\n return (\n bufferLayout.name === bufferName &&\n Boolean(bufferLayout.attributes?.length) &&\n Boolean(geometry.attributes[bufferName])\n );\n}\n\nfunction getInterleavedSourceAttributes(\n geometry: Geometry,\n attributeNames?: string[]\n): Array<[string, GeometryAttribute | undefined]> {\n if (attributeNames) {\n return attributeNames.map(attributeName => [attributeName, geometry.attributes[attributeName]]);\n }\n return Object.entries(geometry.attributes);\n}\n\nfunction writeInterleavedAttribute(\n arrayBuffer: ArrayBuffer,\n vertexCount: number,\n byteStride: number,\n attribute: InterleavedAttribute\n): void {\n const ArrayType = attribute.value.constructor as TypedArrayConstructor;\n const bytesPerElement = ArrayType.BYTES_PER_ELEMENT;\n\n if (attribute.byteOffset % bytesPerElement !== 0 || byteStride % bytesPerElement !== 0) {\n throw new Error(`Attribute ${attribute.sourceName} is not aligned to its component type`);\n }\n\n const target = new ArrayType(arrayBuffer) as any;\n const source = attribute.value as any;\n const elementOffset = attribute.byteOffset / bytesPerElement;\n const elementStride = byteStride / bytesPerElement;\n\n for (let vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) {\n const sourceIndex = vertexIndex * attribute.size;\n const targetIndex = vertexIndex * elementStride + elementOffset;\n for (let componentIndex = 0; componentIndex < attribute.size; componentIndex++) {\n target[targetIndex + componentIndex] = source[sourceIndex + componentIndex];\n }\n }\n}\n\nfunction alignTo(byteOffset: number, alignment: number): number {\n return Math.ceil(byteOffset / alignment) * alignment;\n}\n\n// export function calculateVertexNormals(positions: Float32Array): Uint8Array {\n// let normals = new Uint8Array(positions.length / 3);\n\n// for (let i = 0; i < positions.length; i++) {\n// const vec1 = new Vector3(positions.subarray(i * 3, i + 0, i + 3));\n// const vec2 = new Vector3(positions.subarray(i + 3, i + 6));\n// const vec3 = new Vector3(positions.subarray(i + 6, i + 9));\n\n// const normal = new Vector3(vec1).cross(vec2).normalize();\n// normals.set(normal[0], i + 4);\n// normals.set(normal[1], i + 4 + 1);\n// normals.set(normal[2], i + 2);\n// }\n// const normal = new Vector3(vec1).cross(vec2).normalize();\n// }\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderLayout} from '@luma.gl/core';\n\n/**\n * Extracts a table suitable for `console.table()` from a shader layout to assist in debugging.\n * @param layout shader layout\n * @param name app should provide the most meaningful name, usually the model or pipeline name / id.\n * @returns\n */\nexport function getDebugTableForShaderLayout(\n layout: ShaderLayout,\n name: string\n): Record<string, Record<string, string>> {\n const table: Record<string, Record<string, string>> = {};\n\n const header = 'Values'; // '`Shader Layout for ${name}`;\n\n if (layout.attributes.length === 0 && !layout.varyings?.length) {\n return {'No attributes or varyings': {[header]: 'N/A'}};\n }\n\n for (const attributeDeclaration of layout.attributes) {\n if (attributeDeclaration) {\n const glslDeclaration = `${attributeDeclaration.location} ${attributeDeclaration.name}: ${attributeDeclaration.type}`;\n table[`in ${glslDeclaration}`] = {[header]: attributeDeclaration.stepMode || 'vertex'};\n }\n }\n\n for (const varyingDeclaration of layout.varyings || []) {\n const glslDeclaration = `${varyingDeclaration.location} ${varyingDeclaration.name}`;\n table[`out ${glslDeclaration}`] = {[header]: JSON.stringify(varyingDeclaration)};\n }\n\n return table;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, Framebuffer, RenderPass, Texture} from '@luma.gl/core';\n\nconst DEBUG_FRAMEBUFFER_STATE_KEY = '__debugFramebufferState';\nconst DEFAULT_MARGIN_PX = 8;\n\ntype DebugFramebufferOptions = {\n id: string;\n minimap?: boolean;\n opaque?: boolean;\n top?: string;\n left?: string;\n rgbaScale?: number;\n};\n\ntype DebugFramebufferState = {\n flushing: boolean;\n queuedFramebuffers: Framebuffer[];\n};\n\n/**\n * Debug utility to blit queued offscreen framebuffers into the default framebuffer\n * without CPU readback. Currently implemented for WebGL only.\n */\nexport function debugFramebuffer(\n renderPass: RenderPass,\n source: Framebuffer | Texture | null,\n options: DebugFramebufferOptions\n): void {\n if (renderPass.device.type !== 'webgl') {\n return;\n }\n\n const state = getDebugFramebufferState(renderPass.device);\n if (state.flushing) {\n return;\n }\n\n if (isDefaultRenderPass(renderPass)) {\n flushDebugFramebuffers(renderPass, options, state);\n return;\n }\n\n if (source && isFramebuffer(source) && source.handle !== null) {\n if (!state.queuedFramebuffers.includes(source)) {\n state.queuedFramebuffers.push(source);\n }\n }\n}\n\nfunction flushDebugFramebuffers(\n renderPass: RenderPass,\n options: DebugFramebufferOptions,\n state: DebugFramebufferState\n): void {\n if (state.queuedFramebuffers.length === 0) {\n return;\n }\n\n const webglDevice = renderPass.device as Device & {gl: WebGL2RenderingContext};\n const {gl} = webglDevice;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n const [targetWidth, targetHeight] = renderPass.device\n .getDefaultCanvasContext()\n .getDrawingBufferSize();\n\n let topPx = parseCssPixel(options.top, DEFAULT_MARGIN_PX);\n const leftPx = parseCssPixel(options.left, DEFAULT_MARGIN_PX);\n\n state.flushing = true;\n try {\n for (const framebuffer of state.queuedFramebuffers) {\n const [targetX0, targetY0, targetX1, targetY1, previewHeight] = getOverlayRect({\n framebuffer,\n targetWidth,\n targetHeight,\n topPx,\n leftPx,\n minimap: options.minimap\n });\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer.handle as WebGLFramebuffer | null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);\n gl.blitFramebuffer(\n 0,\n 0,\n framebuffer.width,\n framebuffer.height,\n targetX0,\n targetY0,\n targetX1,\n targetY1,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST\n );\n\n topPx += previewHeight + DEFAULT_MARGIN_PX;\n }\n } finally {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n state.flushing = false;\n }\n}\n\nfunction getOverlayRect(options: {\n framebuffer: Framebuffer;\n targetWidth: number;\n targetHeight: number;\n topPx: number;\n leftPx: number;\n minimap?: boolean;\n}): [number, number, number, number, number] {\n const {framebuffer, targetWidth, targetHeight, topPx, leftPx, minimap} = options;\n const maxWidth = minimap ? Math.max(Math.floor(targetWidth / 4), 1) : targetWidth;\n const maxHeight = minimap ? Math.max(Math.floor(targetHeight / 4), 1) : targetHeight;\n const scale = Math.min(maxWidth / framebuffer.width, maxHeight / framebuffer.height);\n const previewWidth = Math.max(Math.floor(framebuffer.width * scale), 1);\n const previewHeight = Math.max(Math.floor(framebuffer.height * scale), 1);\n const targetX0 = leftPx;\n const targetY0 = Math.max(targetHeight - topPx - previewHeight, 0);\n const targetX1 = targetX0 + previewWidth;\n const targetY1 = targetY0 + previewHeight;\n return [targetX0, targetY0, targetX1, targetY1, previewHeight];\n}\n\nfunction getDebugFramebufferState(device: Device): DebugFramebufferState {\n device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] ||= {\n flushing: false,\n queuedFramebuffers: []\n } satisfies DebugFramebufferState;\n return device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] as DebugFramebufferState;\n}\n\nfunction isFramebuffer(value: Framebuffer | Texture): value is Framebuffer {\n return 'colorAttachments' in value;\n}\n\nfunction isDefaultRenderPass(renderPass: RenderPass): boolean {\n const framebuffer = renderPass.props.framebuffer as {handle?: unknown} | null;\n return !framebuffer || framebuffer.handle === null;\n}\n\nfunction parseCssPixel(value: string | undefined, defaultValue: number): number {\n if (!value) {\n return defaultValue;\n }\n const parsedValue = Number.parseInt(value, 10);\n return Number.isFinite(parsedValue) ? parsedValue : defaultValue;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Fast partial deep equal for prop.\n *\n * @param a Prop\n * @param b Prop to compare against `a`\n * @param depth Depth to which to recurse in nested Objects/Arrays. Use 0 (default) for shallow comparison, -1 for infinite depth\n */\n/* eslint-disable complexity */\nexport function deepEqual(a: any, b: any, depth: number): boolean {\n if (a === b) {\n return true;\n }\n if (!depth || !a || !b) {\n return false;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(b)) {\n return false;\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n if (!b.hasOwnProperty(key)) {\n return false;\n }\n if (!deepEqual(a[key], b[key], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {getBufferLayoutAttributeNames, type BufferLayout} from '@luma.gl/core';\n\n/** BufferLayoutHelper is a helper class that should not be used directly by applications */\nexport class BufferLayoutHelper {\n bufferLayouts: BufferLayout[];\n\n constructor(bufferLayouts: BufferLayout[]) {\n this.bufferLayouts = bufferLayouts;\n }\n\n getBufferLayout(name: string): BufferLayout | null {\n return this.bufferLayouts.find(layout => layout.name === name) || null;\n }\n\n /** Get attribute names from a BufferLayout */\n getAttributeNamesForBuffer(bufferLayout: BufferLayout): string[] {\n return getBufferLayoutAttributeNames(bufferLayout);\n }\n\n mergeBufferLayouts(\n bufferLayouts1: BufferLayout[],\n bufferLayouts2: BufferLayout[]\n ): BufferLayout[] {\n const mergedLayouts = [...bufferLayouts1];\n for (const attribute of bufferLayouts2) {\n const index = mergedLayouts.findIndex(attribute2 => attribute2.name === attribute.name);\n if (index < 0) {\n mergedLayouts.push(attribute);\n } else {\n mergedLayouts[index] = attribute;\n }\n }\n return mergedLayouts;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n getBufferLayoutAttributeNames,\n getMinimumAttributeLocation,\n getShaderAttributeLocationMap,\n type BufferLayout,\n type ShaderLayout\n} from '@luma.gl/core';\n\nexport function sortedBufferLayoutByShaderSourceLocations(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[]\n): BufferLayout[] {\n const shaderLayoutMap = getShaderAttributeLocationMap(shaderLayout);\n\n const sortedLayout = bufferLayout.slice();\n sortedLayout.sort((a, b) => {\n const minLocationA = getMinimumAttributeLocation(\n getBufferLayoutAttributeNames(a).map(attributeName => shaderLayoutMap[attributeName])\n );\n const minLocationB = getMinimumAttributeLocation(\n getBufferLayoutAttributeNames(b).map(attributeName => shaderLayoutMap[attributeName])\n );\n\n return minLocationA - minLocationB;\n });\n\n return sortedLayout;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ComputeShaderLayout, ShaderLayout} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\ntype AnyShaderLayout = ShaderLayout | ComputeShaderLayout;\n\nexport function mergeShaderModuleBindingsIntoLayout<TShaderLayout extends AnyShaderLayout>(\n shaderLayout: TShaderLayout | null | undefined,\n modules: ShaderModule[]\n): TShaderLayout | null | undefined {\n if (!shaderLayout || !modules.some(module => module.bindingLayout?.length)) {\n return shaderLayout;\n }\n\n const mergedLayout = {\n ...shaderLayout,\n bindings: shaderLayout.bindings.map(binding => ({...binding}))\n } as TShaderLayout;\n\n if ('attributes' in (shaderLayout || {})) {\n (mergedLayout as ShaderLayout).attributes = (shaderLayout as ShaderLayout)?.attributes || [];\n }\n\n for (const module of modules) {\n for (const bindingLayout of module.bindingLayout || []) {\n for (const relatedBindingName of getRelatedBindingNames(bindingLayout.name)) {\n const binding = mergedLayout.bindings.find(\n candidate => candidate.name === relatedBindingName\n );\n if (binding?.group === 0) {\n binding.group = bindingLayout.group;\n }\n if (binding && bindingLayout.visibility !== undefined) {\n binding.visibility = bindingLayout.visibility;\n }\n }\n }\n }\n\n return mergedLayout;\n}\n\nexport function mergeInferredShaderLayout(\n shaderLayout: ShaderLayout | null | undefined,\n inferredShaderLayout: ShaderLayout | null | undefined,\n inferredAttributeNames: readonly string[] = []\n): ShaderLayout | null | undefined {\n if (!shaderLayout) {\n return inferredShaderLayout;\n }\n if (!inferredShaderLayout) {\n return shaderLayout;\n }\n\n return {\n ...shaderLayout,\n attributes: shaderLayout.attributes.length\n ? mergeAttributeLayouts(\n shaderLayout.attributes,\n inferredShaderLayout.attributes.filter(attribute =>\n inferredAttributeNames.includes(attribute.name)\n )\n )\n : inferredShaderLayout.attributes,\n bindings: mergeBindingLayouts(shaderLayout.bindings, inferredShaderLayout.bindings)\n };\n}\n\nexport function shaderModuleHasUniforms(module: ShaderModule): boolean {\n return Boolean(module.uniformTypes && !isObjectEmpty(module.uniformTypes));\n}\n\nexport function mergeShaderModules(\n explicitModules: ShaderModule[] | undefined,\n shaderInputModules: ShaderModule[] | undefined\n): ShaderModule[] {\n const modules: ShaderModule[] = [];\n const moduleNames = new Set<string>();\n\n for (const module of [...(explicitModules || []), ...(shaderInputModules || [])]) {\n if (!moduleNames.has(module.name)) {\n moduleNames.add(module.name);\n modules.push(module);\n }\n }\n\n return modules;\n}\n\n/** Returns binding-name aliases that should share the module-declared bind group. */\nfunction getRelatedBindingNames(bindingName: string): string[] {\n const bindingNames = new Set<string>([bindingName, `${bindingName}Uniforms`]);\n\n if (!bindingName.endsWith('Uniforms')) {\n bindingNames.add(`${bindingName}Sampler`);\n }\n\n return [...bindingNames];\n}\n\nfunction isObjectEmpty(obj: object): boolean {\n for (const _key in obj) {\n return false;\n }\n return true;\n}\n\nfunction mergeBindingLayouts<TBindingLayout extends ShaderLayout['bindings'][number]>(\n explicitBindings: TBindingLayout[],\n inferredBindings: TBindingLayout[]\n): TBindingLayout[] {\n const mergedBindings = explicitBindings.map(binding => ({...binding}));\n const explicitBindingNames = new Set(explicitBindings.map(binding => binding.name));\n const explicitBindingLocations = new Set(\n explicitBindings.map(binding => `${binding.group}:${binding.location}`)\n );\n\n for (const inferredBinding of inferredBindings) {\n const inferredBindingLocation = `${inferredBinding.group}:${inferredBinding.location}`;\n if (\n !explicitBindingNames.has(inferredBinding.name) &&\n !explicitBindingLocations.has(inferredBindingLocation)\n ) {\n mergedBindings.push({...inferredBinding});\n }\n }\n\n return mergedBindings;\n}\n\nfunction mergeAttributeLayouts(\n explicitAttributes: ShaderLayout['attributes'],\n inferredAttributes: ShaderLayout['attributes']\n): ShaderLayout['attributes'] {\n const mergedAttributes = explicitAttributes.map(attribute => ({...attribute}));\n const explicitAttributesByName = new Map(\n explicitAttributes.map(attribute => [attribute.name, attribute])\n );\n const explicitAttributesByLocation = new Map(\n explicitAttributes.map(attribute => [attribute.location, attribute])\n );\n\n for (const inferredAttribute of inferredAttributes) {\n const explicitByName = explicitAttributesByName.get(inferredAttribute.name);\n if (explicitByName) {\n if (\n explicitByName.type !== inferredAttribute.type ||\n explicitByName.location !== inferredAttribute.location\n ) {\n throw new Error(\n `Shader attribute \"${inferredAttribute.name}\" conflicts with its inferred type or location`\n );\n }\n continue;\n }\n\n const explicitByLocation = explicitAttributesByLocation.get(inferredAttribute.location);\n if (explicitByLocation) {\n throw new Error(\n `Shader attributes \"${explicitByLocation.name}\" and \"${inferredAttribute.name}\" both use location ${inferredAttribute.location}`\n );\n }\n\n mergedAttributes.push({...inferredAttribute});\n }\n\n return mergedAttributes;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CompositeShaderType} from '@luma.gl/core';\nimport {log} from '@luma.gl/core';\n// import type {VariableShaderType, UniformValue, UniformFormat, UniformInfoDevice, Texture, Sampler} from '@luma.gl/core';\nimport {\n getShaderModuleDependencies,\n ShaderModule,\n ShaderModuleUniformValue\n} from '@luma.gl/shadertools';\nimport {splitUniformsAndBindings} from './model/split-uniforms-and-bindings';\nimport type {TextureBindingSource} from './dynamic-texture/texture-binding-source';\n\n/** Shader binding accepted by ShaderInputs, including deferred texture binding sources. */\nexport type ShaderInputBinding = Binding | TextureBindingSource;\n\nexport type ShaderInputsOptions = {\n disableWarnings?: boolean;\n};\n\nexport type ShaderInputsProps<\n ShaderPropsT extends Partial<Record<string, Record<string, unknown>>>\n> = Partial<{[P in keyof ShaderPropsT]?: Partial<ShaderPropsT[P]>}> & {\n /** Shader resource bindings that are not owned by a shader module. */\n bindings?: Record<string, ShaderInputBinding>;\n};\n\ntype ShaderInputsModule = Pick<\n ShaderModule<any, any, any>,\n 'bindingLayout' | 'defaultUniforms' | 'dependencies' | 'getUniforms' | 'name' | 'uniformTypes'\n>;\n\n/**\n * ShaderInputs holds uniform and binding values for one or more shader modules,\n * - It can generate binary data for any uniform buffer\n * - It can manage a uniform buffer for each block\n * - It can update managed uniform buffers with a single call\n * - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.\n */\nexport class ShaderInputs<\n ShaderPropsT extends Partial<Record<string, Record<string, unknown>>> = Partial<\n Record<string, Record<string, unknown>>\n >\n> {\n options: Required<ShaderInputsOptions> = {\n disableWarnings: false\n };\n\n /** Registered shader modules, including resolved dependencies. */\n // @ts-ignore Fix typings\n modules: Readonly<{[P in keyof ShaderPropsT]: ShaderInputsModule}>;\n\n /** Stores the uniform values for each module */\n moduleUniforms: Record<keyof ShaderPropsT, Record<string, ShaderModuleUniformValue>>;\n /** Stores resource bindings for each module. */\n moduleBindings: Record<keyof ShaderPropsT, Record<string, ShaderInputBinding>>;\n /** Stores shader resource bindings that are not owned by a shader module. */\n directBindings: Record<string, ShaderInputBinding> = {};\n /** Tracks if uniforms have changed */\n // moduleUniformsChanged: Record<keyof ShaderPropsT, false | string>;\n\n /**\n * Creates shader input storage for one or more shader modules.\n * @param modules Initial shader modules keyed by module name.\n * @param options Shader input behavior options.\n */\n constructor(\n // @ts-ignore Fix typings\n modules: {[P in keyof ShaderPropsT]?: ShaderInputsModule},\n options?: ShaderInputsOptions\n ) {\n Object.assign(this.options, options);\n\n // Extract modules with dependencies\n const resolvedModules = getShaderModuleDependencies(\n Object.values(modules).filter(isShaderInputsModuleWithDependencies)\n );\n for (const resolvedModule of resolvedModules) {\n // @ts-ignore\n modules[resolvedModule.name] = resolvedModule;\n }\n\n log.log(1, 'Creating ShaderInputs with modules', Object.keys(modules))();\n\n // Store the module definitions and create storage for uniform values and binding values, per module\n // @ts-ignore Fix typings\n this.modules = modules as {[P in keyof ShaderPropsT]: ShaderInputsModule};\n this.moduleUniforms = {} as Record<\n keyof ShaderPropsT,\n Record<string, ShaderModuleUniformValue>\n >;\n this.moduleBindings = {} as Record<keyof ShaderPropsT, Record<string, ShaderInputBinding>>;\n\n // Initialize the modules\n for (const [name, module] of Object.entries(modules)) {\n if (module) {\n this._addModule(module);\n if (module.name && name !== module.name && !this.options.disableWarnings) {\n log.warn(`Module name: ${name} vs ${module.name}`)();\n }\n }\n }\n }\n\n /** Destroy */\n destroy(): void {}\n\n /**\n * Set module props\n */\n setProps(props: ShaderInputsProps<ShaderPropsT>): void {\n if (props.bindings) {\n Object.assign(this.directBindings, props.bindings);\n }\n\n for (const name of Object.keys(props)) {\n if (name === 'bindings') {\n continue;\n }\n\n const moduleName = name as keyof ShaderPropsT;\n const moduleProps = props[moduleName] || {};\n const module = this.modules[moduleName];\n if (!module) {\n // Ignore props for unregistered modules\n if (!this.options.disableWarnings) {\n log.warn(`Module ${name} not found`)();\n }\n } else {\n const oldUniforms = this.moduleUniforms[moduleName];\n const oldBindings = this.moduleBindings[moduleName];\n const uniformsAndBindings =\n module.getUniforms?.(moduleProps, oldUniforms) || (moduleProps as any);\n\n const {uniforms, bindings} = splitUniformsAndBindings(\n uniformsAndBindings,\n module.uniformTypes as Readonly<Record<string, CompositeShaderType>>\n );\n this.moduleUniforms[moduleName] = mergeModuleUniforms(\n oldUniforms as Record<string, ShaderModuleUniformValue>,\n uniforms,\n module.uniformTypes as Readonly<Record<string, CompositeShaderType>>\n );\n this.moduleBindings[moduleName] = {...oldBindings, ...bindings};\n // this.moduleUniformsChanged ||= moduleName;\n }\n\n // console.log(`setProps(${String(moduleName)}`, moduleName, this.moduleUniforms[moduleName])\n }\n }\n\n /** Returns registered shader modules, including resolved dependencies. */\n getModules(): ShaderModule[] {\n return Object.values(this.modules) as ShaderModule[];\n }\n\n /**\n * Adds shader modules that should participate in subsequent uniform and binding updates.\n * Module dependencies are resolved before new module state is initialized.\n * @param modules Shader modules to register after construction.\n */\n addModules(modules: ShaderInputsModule[]): void {\n const modulesToAdd = getShaderModuleDependencies(modules);\n\n for (const module of modulesToAdd) {\n const moduleName = module.name as keyof ShaderPropsT;\n if (!this.modules[moduleName]) {\n // @ts-ignore The ShaderInputs module registry is intentionally extended at runtime.\n this.modules[moduleName] = module;\n this._addModule(module);\n }\n }\n }\n\n /** Get all uniform values for all modules */\n getUniformValues(): Partial<\n Record<keyof ShaderPropsT, Record<string, ShaderModuleUniformValue>>\n > {\n return this.moduleUniforms;\n }\n\n /** Merges concrete and deferred bindings for the shader from the registered modules. */\n getBindingValues(): Record<string, ShaderInputBinding> {\n const bindings = {} as Record<string, ShaderInputBinding>;\n for (const moduleBindings of Object.values(this.moduleBindings)) {\n Object.assign(bindings, moduleBindings);\n }\n Object.assign(bindings, this.directBindings);\n return bindings;\n }\n\n /**\n * Gets binding values for a single shader module without flattening them into the full shader map.\n *\n * This is used by systems such as {@link ShaderPassRenderer} that execute one shader module at a\n * time and need the defaults for just that module.\n */\n getModuleBindingValues(\n moduleName: keyof ShaderPropsT | string\n ): Record<string, ShaderInputBinding> {\n const moduleBindings = this.moduleBindings[moduleName as keyof ShaderPropsT];\n return moduleBindings ? {...moduleBindings} : {};\n }\n\n // INTERNAL\n\n /** Return a debug table that can be used for console.table() or log.table() */\n getDebugTable(): Record<string, Record<string, unknown>> {\n const table: Record<string, Record<string, unknown>> = {};\n for (const [moduleName, module] of Object.entries(this.moduleUniforms)) {\n for (const [key, value] of Object.entries(module)) {\n table[`${moduleName}.${key}`] = {\n type: this.modules[moduleName].uniformTypes?.[key as keyof ShaderPropsT],\n value: String(value)\n };\n }\n }\n return table;\n }\n\n _addModule(module: ShaderInputsModule): void {\n const moduleName = module.name as keyof ShaderPropsT;\n // Get default uniforms from module\n this.moduleUniforms[moduleName] = mergeModuleUniforms(\n {},\n (module.defaultUniforms || {}) as Record<string, ShaderModuleUniformValue>,\n module.uniformTypes as Readonly<Record<string, CompositeShaderType>>\n );\n this.moduleBindings[moduleName] = {};\n }\n}\n\nfunction mergeModuleUniforms(\n currentUniforms: Record<string, ShaderModuleUniformValue> = {},\n nextUniforms: Record<string, ShaderModuleUniformValue> = {},\n uniformTypes: Readonly<Record<string, CompositeShaderType>> = {}\n): Record<string, ShaderModuleUniformValue> {\n const mergedUniforms = {...currentUniforms};\n for (const [key, value] of Object.entries(nextUniforms)) {\n if (value !== undefined) {\n mergedUniforms[key] = mergeModuleUniformValue(currentUniforms[key], value, uniformTypes[key]);\n }\n }\n return mergedUniforms;\n}\n\nfunction mergeModuleUniformValue(\n currentValue: ShaderModuleUniformValue | undefined,\n nextValue: ShaderModuleUniformValue,\n uniformType: CompositeShaderType | undefined\n): ShaderModuleUniformValue {\n if (!uniformType || typeof uniformType === 'string') {\n return cloneModuleUniformValue(nextValue);\n }\n\n if (Array.isArray(uniformType)) {\n if (isPackedUniformArrayValue(nextValue) || !Array.isArray(nextValue)) {\n return cloneModuleUniformValue(nextValue);\n }\n\n const currentArray: Array<ShaderModuleUniformValue | undefined> =\n Array.isArray(currentValue) && !isPackedUniformArrayValue(currentValue)\n ? [...currentValue]\n : [];\n const mergedArray = currentArray.slice();\n for (let index = 0; index < nextValue.length; index++) {\n const elementValue = nextValue[index];\n if (elementValue !== undefined) {\n mergedArray[index] = mergeModuleUniformValue(\n currentArray[index],\n elementValue,\n uniformType[0] as CompositeShaderType\n );\n }\n }\n return mergedArray;\n }\n\n if (!isPlainUniformObject(nextValue)) {\n return cloneModuleUniformValue(nextValue);\n }\n\n const uniformStruct = uniformType as Record<string, CompositeShaderType>;\n const currentObject = isPlainUniformObject(currentValue) ? currentValue : {};\n const mergedObject: Record<string, ShaderModuleUniformValue | undefined> = {...currentObject};\n for (const [key, value] of Object.entries(nextValue)) {\n if (value !== undefined) {\n mergedObject[key] = mergeModuleUniformValue(currentObject[key], value, uniformStruct[key]);\n }\n }\n return mergedObject as ShaderModuleUniformValue;\n}\n\nfunction cloneModuleUniformValue(value: ShaderModuleUniformValue): ShaderModuleUniformValue {\n if (ArrayBuffer.isView(value)) {\n return Array.prototype.slice.call(value) as ShaderModuleUniformValue;\n }\n\n if (Array.isArray(value)) {\n if (isPackedUniformArrayValue(value)) {\n return value.slice() as ShaderModuleUniformValue;\n }\n\n const compositeArray = value as ReadonlyArray<ShaderModuleUniformValue | undefined>;\n return compositeArray.map(element =>\n element === undefined ? undefined : cloneModuleUniformValue(element)\n ) as ShaderModuleUniformValue;\n }\n\n if (isPlainUniformObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, nestedValue]) => [\n key,\n nestedValue === undefined ? undefined : cloneModuleUniformValue(nestedValue)\n ])\n ) as ShaderModuleUniformValue;\n }\n\n return value;\n}\n\nfunction isPackedUniformArrayValue(\n value: unknown\n): value is ReadonlyArray<number> | ArrayBufferView {\n return (\n ArrayBuffer.isView(value) ||\n (Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number'))\n );\n}\n\nfunction isPlainUniformObject(\n value: unknown\n): value is Record<string, ShaderModuleUniformValue | undefined> {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !ArrayBuffer.isView(value)\n );\n}\n\nfunction isShaderInputsModuleWithDependencies(\n module: ShaderInputsModule | undefined\n): module is ShaderInputsModule & {dependencies: NonNullable<ShaderInputsModule['dependencies']>} {\n return Boolean(module?.dependencies);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CompositeShaderType, UniformValue} from '@luma.gl/core';\nimport type {ShaderModuleUniformValue} from '@luma.gl/shadertools';\nimport {isNumericArray} from '@math.gl/types';\nimport type {TextureBindingSource} from '../dynamic-texture/texture-binding-source';\n\n/** Shader input value routed through the binding map. */\ntype ShaderInputBinding = Binding | TextureBindingSource;\n\nexport function isUniformValue(value: unknown): value is UniformValue {\n return isNumericArray(value) || typeof value === 'number' || typeof value === 'boolean';\n}\n\ntype UniformsAndBindings = {\n bindings: Record<string, ShaderInputBinding>;\n uniforms: Record<string, ShaderModuleUniformValue>;\n};\n\nexport function splitUniformsAndBindings(\n uniforms: Record<string, ShaderInputBinding | ShaderModuleUniformValue>,\n uniformTypes: Readonly<Record<string, CompositeShaderType>> = {}\n): UniformsAndBindings {\n const result: UniformsAndBindings = {bindings: {}, uniforms: {}};\n Object.keys(uniforms).forEach(name => {\n const uniform = uniforms[name];\n if (Object.prototype.hasOwnProperty.call(uniformTypes, name) || isUniformValue(uniform)) {\n result.uniforms[name] = uniform as ShaderModuleUniformValue;\n } else {\n result.bindings[name] = uniform as ShaderInputBinding;\n }\n });\n\n return result;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {BufferMapCallback, BufferProps, Device, Binding as CoreBinding} from '@luma.gl/core';\nimport {Buffer} from '@luma.gl/core';\nimport {uid} from '../utils/uid';\n\n/** Controls whether a {@link DynamicBuffer} keeps a CPU-side debug mirror of recent writes. */\nexport type DynamicBufferDebugProps =\n | boolean\n | {\n /** Maximum number of bytes retained in {@link DynamicBuffer.debugData}. */\n maxByteLength?: number;\n };\n\n/** Construction props for a {@link DynamicBuffer}. */\nexport type DynamicBufferProps = Omit<BufferProps, 'handle' | 'onMapped'> & {\n /** Enables and optionally sizes the CPU-side debug mirror. */\n debugData?: DynamicBufferDebugProps;\n /** Existing immutable buffer to expose through this dynamic wrapper without copying. */\n buffer?: Buffer;\n /** Whether this dynamic wrapper should destroy an adopted `buffer`. Defaults to `true`. */\n ownsBuffer?: boolean;\n};\n\n/** Buffer-like source accepted by dynamic buffer range helpers. */\nexport type BufferBindingSource = Buffer | DynamicBuffer;\n\n/** Binding range that may point at either a {@link Buffer} or a {@link DynamicBuffer}. */\nexport type DynamicBufferRange = {\n /** Buffer source for the binding range. */\n buffer: BufferBindingSource;\n /** Byte offset into the current backing buffer. */\n offset?: number;\n /** Byte length of the binding range. */\n size?: number;\n};\n\n/** Generic buffer range binding accepted by engine binding resolution helpers. */\nexport type BufferRangeBinding = {\n /** Buffer source for the binding range. */\n buffer: BufferBindingSource;\n /** Byte offset into the current backing buffer. */\n offset?: number;\n /** Byte length of the binding range. */\n size?: number;\n};\n\nconst DEFAULT_MAX_DEBUG_DATA_BYTE_LENGTH = Buffer.DEBUG_DATA_MAX_LENGTH;\n\n/**\n * Mutable engine-level wrapper around an immutable core {@link Buffer}.\n *\n * `DynamicBuffer` keeps a stable application object while allowing the backing\n * GPU buffer to be replaced on resize. Engine classes such as {@link Model} and\n * {@link Material} resolve it to the current backing buffer at draw time and\n * invalidate cached bindings when {@link generation} changes.\n */\nexport class DynamicBuffer {\n /** Device that owns the backing buffer. */\n readonly device: Device;\n /** Application-provided or generated identifier. */\n readonly id: string;\n /** Ready promise provided for compatibility with other dynamic resources. */\n readonly ready: Promise<Buffer>;\n /** Usage flags applied to every backing buffer created by this wrapper. */\n readonly usage: number;\n /** Normalized buffer props reused when the backing buffer is recreated. */\n readonly props: Readonly<DynamicBufferProps>;\n\n /** Dynamic buffers are synchronously ready after construction. */\n isReady = true;\n /** Whether {@link destroy} has been called. */\n destroyed = false;\n /** Monotonic version that increments whenever the backing buffer is replaced. */\n generation = 0;\n /** Last update timestamp for writes, reads that populate debug data, or resize operations. */\n updateTimestamp: number;\n /** Optional CPU-side mirror of recent writes and readbacks for debugging. */\n debugData: ArrayBuffer = new ArrayBuffer(0);\n\n private readonly _debugDataEnabled: boolean;\n private readonly _maxDebugDataByteLength: number;\n private _ownsBuffer: boolean;\n private _buffer: Buffer;\n\n /** Current immutable core buffer backing this dynamic wrapper. */\n get buffer(): Buffer {\n return this._buffer;\n }\n\n /** Current byte length of the backing buffer. */\n get byteLength(): number {\n return this._buffer.byteLength;\n }\n\n /** String tag used by `Object.prototype.toString`. */\n get [Symbol.toStringTag](): string {\n return 'DynamicBuffer';\n }\n\n /** Human-readable debug string. */\n toString(): string {\n return `DynamicBuffer:\"${this.id}\":${this.byteLength}B`;\n }\n\n /** Compact serialization for assertion diffs and structured debug logs. */\n toJSON(): string {\n return this.toString();\n }\n\n /** Creates a dynamic buffer and its initial backing {@link Buffer}. */\n constructor(device: Device, props: DynamicBufferProps) {\n const {\n debugData: debugDataProps = false,\n buffer: adoptedBuffer,\n ownsBuffer = true,\n ...bufferProps\n } = props;\n if (adoptedBuffer && adoptedBuffer.device !== device) {\n throw new Error('DynamicBuffer adopted buffers must belong to the supplied device');\n }\n if (adoptedBuffer && (bufferProps.byteLength !== undefined || bufferProps.data !== undefined)) {\n throw new Error('DynamicBuffer cannot combine an adopted buffer with byteLength or data');\n }\n\n const id = props.id || adoptedBuffer?.id || uid('dynamic-buffer');\n const normalizedBufferProps: DynamicBufferProps = {\n ...bufferProps,\n id,\n usage: bufferProps.usage ?? adoptedBuffer?.usage,\n indexType: bufferProps.indexType ?? adoptedBuffer?.indexType\n };\n\n if ((normalizedBufferProps.usage || 0) & Buffer.INDEX && !normalizedBufferProps.indexType) {\n if (bufferProps.data instanceof Uint32Array) {\n normalizedBufferProps.indexType = 'uint32';\n } else if (bufferProps.data instanceof Uint16Array) {\n normalizedBufferProps.indexType = 'uint16';\n } else if (bufferProps.data instanceof Uint8Array) {\n normalizedBufferProps.indexType = 'uint8';\n }\n }\n\n delete normalizedBufferProps.data;\n delete normalizedBufferProps.byteOffset;\n\n this.device = device;\n this.id = id;\n this.props = normalizedBufferProps;\n this.usage = normalizedBufferProps.usage || 0;\n this._debugDataEnabled = Boolean(debugDataProps);\n this._maxDebugDataByteLength =\n typeof debugDataProps === 'object' && debugDataProps.maxByteLength !== undefined\n ? debugDataProps.maxByteLength\n : DEFAULT_MAX_DEBUG_DATA_BYTE_LENGTH;\n this._ownsBuffer = ownsBuffer;\n\n this._buffer = adoptedBuffer ?? this.device.createBuffer({...bufferProps, id});\n this.ready = Promise.resolve(this._buffer);\n this.updateTimestamp = this._buffer.updateTimestamp;\n\n this._resetDebugData(this._buffer.byteLength);\n if (bufferProps.data) {\n this._writeDebugData(bufferProps.data, bufferProps.byteOffset || 0);\n }\n }\n\n /**\n * Writes bytes into the current backing buffer.\n *\n * @param data - Bytes or typed-array view to upload.\n * @param byteOffset - Destination byte offset in the backing buffer.\n */\n write(data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView, byteOffset: number = 0): void {\n this._buffer.write(data, byteOffset);\n this._touch();\n this._writeDebugData(data, byteOffset);\n }\n\n /**\n * Maps the current backing buffer for writing and mirrors the written range when debug data is enabled.\n *\n * @param callback - Callback invoked with the mapped range.\n * @param byteOffset - Byte offset of the mapped range.\n * @param byteLength - Byte length of the mapped range.\n */\n async mapAndWriteAsync(\n callback: BufferMapCallback<void | Promise<void>>,\n byteOffset: number = 0,\n byteLength: number = this.byteLength - byteOffset\n ): Promise<void> {\n let copiedBytes: Uint8Array | null = null;\n await this._buffer.mapAndWriteAsync(\n async (arrayBuffer, lifetime) => {\n await callback(arrayBuffer, lifetime);\n copiedBytes = new Uint8Array(arrayBuffer.slice(0, byteLength));\n },\n byteOffset,\n byteLength\n );\n this._touch();\n if (copiedBytes) {\n this._writeDebugData(copiedBytes, byteOffset);\n }\n }\n\n /**\n * Reads bytes from the current backing buffer.\n *\n * @param byteOffset - Source byte offset in the backing buffer.\n * @param byteLength - Number of bytes to read.\n */\n async readAsync(\n byteOffset: number = 0,\n byteLength = this.byteLength - byteOffset\n ): Promise<Uint8Array> {\n const data = await this._buffer.readAsync(byteOffset, byteLength);\n if (this._writeDebugData(data, byteOffset)) {\n this._touch();\n }\n return data;\n }\n\n /**\n * Maps the current backing buffer for reading.\n *\n * @param callback - Callback invoked with the mapped range.\n * @param byteOffset - Byte offset of the mapped range.\n * @param byteLength - Byte length of the mapped range.\n */\n async mapAndReadAsync<T>(\n callback: BufferMapCallback<T>,\n byteOffset: number = 0,\n byteLength: number = this.byteLength - byteOffset\n ): Promise<T> {\n let copiedBytes: Uint8Array | null = null;\n const result = await this._buffer.mapAndReadAsync(\n async (arrayBuffer, lifetime) => {\n copiedBytes = new Uint8Array(arrayBuffer.slice(0));\n return await callback(arrayBuffer, lifetime);\n },\n byteOffset,\n byteLength\n );\n if (copiedBytes && this._writeDebugData(copiedBytes, byteOffset)) {\n this._touch();\n }\n return result;\n }\n\n /**\n * Replaces the backing buffer with a new size.\n *\n * @param options.byteLength - New backing buffer byte length.\n * @param options.preserveData - Copies bytes from the old buffer into the new buffer.\n * @param options.copyByteLength - Maximum number of bytes to copy when preserving data.\n * @returns `true` when a new backing buffer was created.\n */\n resize(options: {byteLength: number; preserveData?: boolean; copyByteLength?: number}): boolean {\n const {byteLength, preserveData = false} = options;\n if (byteLength === this.byteLength) {\n return false;\n }\n\n const copyByteLength = Math.min(\n options.copyByteLength ?? Math.min(this.byteLength, byteLength),\n this.byteLength,\n byteLength\n );\n\n const previousBuffer = this._buffer;\n const previousDebugData = this.debugData.slice(0);\n const {\n data: _initialData,\n byteOffset: _initialByteOffset,\n ...resizableBufferProps\n } = this.props;\n const nextBuffer = this.device.createBuffer({\n ...resizableBufferProps,\n byteLength\n });\n\n if (preserveData && copyByteLength > 0) {\n this._copyBufferContents(previousBuffer, nextBuffer, copyByteLength);\n }\n\n this._buffer = nextBuffer;\n this._resetDebugData(byteLength);\n if (preserveData && previousDebugData.byteLength > 0) {\n this._writeDebugData(previousDebugData, 0);\n }\n\n if (this._ownsBuffer) {\n previousBuffer.destroy();\n }\n this._ownsBuffer = true;\n this.generation++;\n this._touch();\n return true;\n }\n\n /**\n * Grows the backing buffer when the requested size exceeds the current size.\n *\n * @param byteLength - Minimum required byte length.\n * @param options.preserveData - Copies existing bytes when growth is required.\n * @returns `true` when the backing buffer grew.\n */\n ensureSize(byteLength: number, options?: {preserveData?: boolean}): boolean {\n if (byteLength <= this.byteLength) {\n return false;\n }\n\n return this.resize({\n byteLength,\n preserveData: options?.preserveData\n });\n }\n\n /**\n * Returns the current backing buffer or a range binding over it.\n *\n * @param range - Optional byte range for uniform/storage buffer bindings.\n */\n getBinding(range?: {offset?: number; size?: number}): CoreBinding {\n if (range?.offset === undefined && range?.size === undefined) {\n return this._buffer;\n }\n\n return {\n buffer: this._buffer,\n offset: range?.offset,\n size: range?.size\n };\n }\n\n /** Destroys the current backing buffer and clears debug data. */\n destroy(): void {\n if (!this.destroyed) {\n if (this._ownsBuffer) {\n this._buffer.destroy();\n }\n this.destroyed = true;\n this.debugData = new ArrayBuffer(0);\n }\n }\n\n private _copyBufferContents(\n sourceBuffer: Buffer,\n destinationBuffer: Buffer,\n byteLength: number\n ): void {\n const copyByteLength =\n this.device.type === 'webgpu' ? Math.ceil(byteLength / 4) * 4 : byteLength;\n const commandEncoder = this.device.createCommandEncoder();\n commandEncoder.copyBufferToBuffer({\n sourceBuffer,\n destinationBuffer,\n size: copyByteLength\n });\n this.device.submit(commandEncoder.finish());\n }\n\n private _touch(): void {\n this.updateTimestamp = this.device.incrementTimestamp();\n }\n\n private _resetDebugData(byteLength: number): void {\n if (!this._debugDataEnabled) {\n this.debugData = new ArrayBuffer(0);\n return;\n }\n\n this.debugData = new ArrayBuffer(Math.min(byteLength, this._maxDebugDataByteLength));\n }\n\n private _writeDebugData(\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView,\n byteOffset: number\n ): boolean {\n if (\n !this._debugDataEnabled ||\n this.debugData.byteLength === 0 ||\n byteOffset >= this.debugData.byteLength\n ) {\n return false;\n }\n\n const source = ArrayBuffer.isView(data)\n ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n : new Uint8Array(data);\n const target = new Uint8Array(this.debugData);\n const copyByteLength = Math.min(source.byteLength, target.byteLength - byteOffset);\n target.set(source.subarray(0, copyByteLength), byteOffset);\n return copyByteLength > 0;\n }\n}\n\n/** Returns `true` when a value has the structural shape of a buffer range binding. */\nexport function isBufferRangeBinding(binding: unknown): binding is BufferRangeBinding {\n return (\n binding !== null &&\n typeof binding === 'object' &&\n 'buffer' in (binding as Record<string, unknown>)\n );\n}\n\n/** Returns `true` when a range binding points at a {@link DynamicBuffer}. */\nexport function isDynamicBufferRange(binding: unknown): binding is DynamicBufferRange {\n return isBufferRangeBinding(binding) && binding.buffer instanceof DynamicBuffer;\n}\n\n/** Extracts a {@link DynamicBuffer} from a direct binding or range binding. */\nexport function getDynamicBufferFromBinding(binding: unknown): DynamicBuffer | null {\n if (binding instanceof DynamicBuffer) {\n return binding;\n }\n\n if (isBufferRangeBinding(binding) && binding.buffer instanceof DynamicBuffer) {\n return binding.buffer;\n }\n\n return null;\n}\n\n/** Resolves a static or dynamic buffer source to the current core {@link Buffer}. */\nexport function resolveBufferBindingSource(buffer: BufferBindingSource): Buffer {\n return buffer instanceof DynamicBuffer ? buffer.buffer : buffer;\n}\n\n/** Resolves a dynamic buffer range to a core buffer range over the current backing buffer. */\nexport function resolveDynamicBufferRangeBinding(binding: DynamicBufferRange): {\n buffer: Buffer;\n offset?: number;\n size?: number;\n} {\n return resolveBufferRangeBinding(binding);\n}\n\n/** Resolves a buffer range to a core buffer range over the current backing buffer. */\nexport function resolveBufferRangeBinding(binding: BufferRangeBinding): {\n buffer: Buffer;\n offset?: number;\n size?: number;\n} {\n return {\n buffer: resolveBufferBindingSource(binding.buffer),\n offset: binding.offset,\n size: binding.size\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, BindingDeclaration, ComputeShaderLayout, ShaderLayout} from '@luma.gl/core';\nimport {getShaderLayoutBinding} from '@luma.gl/core';\n\n/** Reflected shader binding declarations that accept texture-like engine sources. */\nexport type TextureBindingLayout = Extract<\n BindingDeclaration,\n {type: 'texture' | 'external-texture'}\n>;\n\n/**\n * Engine-level source that resolves into a concrete core texture binding for one shader slot.\n */\nexport interface TextureBindingSource {\n /** Stable resource identifier used in loading and debug messages. */\n readonly id: string;\n /** Whether the source can resolve a concrete binding for the current draw. */\n readonly isReady: boolean;\n /** Monotonic binding generation advanced when concrete draw bindings may need recreation. */\n readonly generation: number;\n /** Device timestamp of the most recent source content or binding identity update. */\n readonly updateTimestamp: number;\n\n /**\n * Resolves this source for one reflected texture binding declaration.\n * @param bindingLayout Reflected `texture` or `external-texture` shader slot.\n * @returns A concrete core binding, or `null` while the source is not ready.\n */\n resolveTextureBinding(bindingLayout: TextureBindingLayout): Binding | null;\n}\n\n/**\n * Returns whether a value is an engine source that resolves texture bindings at draw time.\n * @param value Candidate engine binding value.\n * @returns Whether `value` implements {@link TextureBindingSource}.\n */\nexport function isTextureBindingSource(value: unknown): value is TextureBindingSource {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'resolveTextureBinding' in value &&\n typeof value.resolveTextureBinding === 'function'\n );\n}\n\n/**\n * Returns whether a shader binding declaration accepts a texture binding source.\n * @param bindingLayout Candidate reflected shader binding declaration.\n * @returns Whether `bindingLayout` is a `texture` or `external-texture` declaration.\n */\nexport function isTextureBindingLayout(\n bindingLayout: BindingDeclaration | null\n): bindingLayout is TextureBindingLayout {\n return bindingLayout?.type === 'texture' || bindingLayout?.type === 'external-texture';\n}\n\n/**\n * Looks up the reflected texture binding declaration for one engine binding name.\n *\n * @remarks\n * Models and materials can be asked for bindings before a shader layout has been reflected.\n * In that legacy empty-layout path, `fallbackGroup` synthesizes an ordinary `texture` slot so\n * copied `DynamicTexture` and `VideoTexture` bindings keep their pre-reflection behavior.\n * Native WebGPU `texture_external` resolution still requires the real reflected declaration.\n *\n * @param shaderLayout Reflected shader bindings, or an empty binding list before reflection.\n * @param bindingName Engine binding name to resolve against the shader layout.\n * @param options Texture binding lookup behavior.\n * @param options.fallbackGroup Bind group for the legacy empty-layout ordinary texture fallback.\n * @returns The reflected or synthesized texture binding declaration, or `null` for non-texture slots.\n */\nexport function getTextureBindingLayout(\n shaderLayout: Pick<ShaderLayout | ComputeShaderLayout, 'bindings'>,\n bindingName: string,\n options?: {fallbackGroup?: number}\n): TextureBindingLayout | null {\n const bindingLayout = getShaderLayoutBinding(shaderLayout, bindingName, {\n ignoreWarnings: true\n });\n if (isTextureBindingLayout(bindingLayout)) {\n return bindingLayout;\n }\n return shaderLayout.bindings.length === 0 && options?.fallbackGroup !== undefined\n ? {\n type: 'texture',\n name: bindingName,\n group: options.fallbackGroup,\n location: 0\n }\n : null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n Binding,\n BindingsByGroup,\n CommandEncoder,\n ComputeShaderLayout,\n Device,\n ShaderLayout\n} from '@luma.gl/core';\nimport {Buffer, ExternalTexture, Texture, TextureView, UniformStore} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport {\n DynamicBuffer,\n type DynamicBufferRange,\n getDynamicBufferFromBinding,\n isBufferRangeBinding,\n resolveBufferRangeBinding\n} from '../dynamic-buffer/dynamic-buffer';\nimport {\n getTextureBindingLayout,\n isTextureBindingSource,\n type TextureBindingSource\n} from '../dynamic-texture/texture-binding-source';\nimport {ShaderInputs} from '../shader-inputs';\nimport {shaderModuleHasUniforms} from '../utils/shader-module-utils';\nimport {uid} from '../utils/uid';\nimport {\n getModuleNameFromUniformBinding,\n MATERIAL_BIND_GROUP,\n MaterialFactory\n} from './material-factory';\n\ntype MaterialModuleProps = Partial<Record<string, Record<string, unknown>>>;\n/** Resource accepted by one material binding slot. */\ntype MaterialBinding = Binding | TextureBindingSource | DynamicBuffer | DynamicBufferRange;\ntype MaterialBindings = Record<string, MaterialBinding>;\n/** Shader layout subset needed while resolving texture binding sources. */\ntype AnyShaderLayout = Pick<ShaderLayout | ComputeShaderLayout, 'bindings'>;\ntype MaterialPropsUpdate<TModuleProps extends MaterialModuleProps> = Partial<{\n [P in keyof TModuleProps]?: Partial<TModuleProps[P]>;\n}>;\n\n/** Construction props for one typed {@link Material}. */\nexport type MaterialProps<\n TModuleProps extends MaterialModuleProps = MaterialModuleProps,\n TBindings extends MaterialBindings = MaterialBindings\n> = {\n /** Optional application-provided identifier. */\n id?: string;\n /** Factory that owns the material schema. */\n factory?: MaterialFactory<TModuleProps, TBindings>;\n /** Optional pre-created shader inputs for the material modules. */\n shaderInputs?: ShaderInputs<TModuleProps>;\n /** Shader modules used when a factory is not supplied. */\n modules?: ShaderModule[];\n /** Initial material-owned resource bindings. */\n bindings?: Partial<TBindings>;\n};\n\n/** Structural overrides applied when cloning a {@link Material}. */\nexport type MaterialCloneProps<\n TModuleProps extends MaterialModuleProps = MaterialModuleProps,\n TBindings extends MaterialBindings = MaterialBindings\n> = {\n /** Optional identifier for the cloned material. */\n id?: string;\n /** Replacement material-owned resource bindings. */\n bindings?: Partial<TBindings>;\n /** Additional uniform/module props applied to the clone. */\n moduleProps?: MaterialPropsUpdate<TModuleProps>;\n /** Optional full replacement shader-input store. */\n shaderInputs?: ShaderInputs<TModuleProps>;\n};\n\n/**\n * Material owns bind group `3` resources and uniforms for one material instance.\n *\n * `setProps()` mutates uniform values in place. Structural resource changes are\n * expressed through `clone({...})`, which creates a new material identity.\n */\nexport class Material<\n TModuleProps extends MaterialModuleProps = MaterialModuleProps,\n TBindings extends MaterialBindings = MaterialBindings\n> {\n /** Application-provided identifier. */\n readonly id: string;\n /** Device that owns the material resources. */\n readonly device: Device;\n /** Factory that defines the material schema. */\n readonly factory: MaterialFactory<TModuleProps, TBindings>;\n /** Shader inputs for the material-owned modules. */\n readonly shaderInputs: ShaderInputs<TModuleProps>;\n /** Internal binding store including uniform buffers and resource bindings. */\n readonly bindings: Record<string, MaterialBinding> = {};\n\n private _uniformStore: UniformStore;\n private _bindGroupCacheToken: object = {};\n private _dynamicResourceGenerations: Record<string, number> = {};\n\n constructor(device: Device, props: MaterialProps<TModuleProps, TBindings> = {}) {\n this.id = props.id || uid('material');\n this.device = device;\n\n this.factory =\n props.factory ||\n new MaterialFactory<TModuleProps, TBindings>(device, {\n modules: props.modules || props.shaderInputs?.getModules() || []\n });\n\n const moduleMap = Object.fromEntries(\n (props.shaderInputs?.getModules() || this.factory.modules).map(module => [\n module.name,\n module\n ])\n ) as {[P in keyof TModuleProps]?: ShaderModule[] extends never ? never : any};\n this.shaderInputs = props.shaderInputs || new ShaderInputs<TModuleProps>(moduleMap);\n this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules);\n\n for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) {\n if (this.ownsModule(moduleName) && shaderModuleHasUniforms(module)) {\n const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName);\n this.bindings[`${moduleName}Uniforms`] = uniformBuffer;\n }\n }\n\n this.updateShaderInputs();\n if (props.bindings) {\n this._replaceOwnedBindings(props.bindings);\n }\n }\n\n /** Destroys managed uniform-buffer resources owned by this material. */\n destroy(): void {\n this._uniformStore.destroy();\n }\n\n /** Creates a new material variant with optional structural and uniform overrides. */\n clone(\n props: MaterialCloneProps<TModuleProps, TBindings> = {}\n ): Material<TModuleProps, TBindings> {\n const material = this.factory.createMaterial({\n id: props.id,\n shaderInputs: props.shaderInputs,\n bindings: {\n ...this.getResourceBindings(),\n ...props.bindings\n }\n });\n\n if (!props.shaderInputs) {\n material.setProps(this.shaderInputs.getUniformValues() as MaterialPropsUpdate<TModuleProps>);\n }\n if (props.moduleProps) {\n material.setProps(props.moduleProps);\n }\n material.updateShaderInputs();\n return material;\n }\n\n /** Returns `true` if this material owns the supplied binding name. */\n ownsBinding(bindingName: string): boolean {\n return this.factory.ownsBinding(bindingName);\n }\n\n /** Returns `true` if this material owns the supplied shader module. */\n ownsModule(moduleName: string): boolean {\n return this.factory.ownsModule(moduleName);\n }\n\n /** Updates material uniform/module props in place without changing material identity. */\n setProps(props: MaterialPropsUpdate<TModuleProps>): void {\n this.shaderInputs.setProps(props);\n }\n\n /**\n * Updates managed uniform buffers and shader-input-owned bindings.\n *\n * @param commandEncoder - Optional encoder used to order material uniform\n * uploads with subsequent draw commands.\n */\n updateShaderInputs(commandEncoder?: CommandEncoder): void {\n this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(), commandEncoder);\n const didChange = this._setOwnedBindings(this.shaderInputs.getBindingValues());\n if (didChange) {\n this._bindGroupCacheToken = {};\n }\n }\n\n /** Returns the material-owned resource bindings without internal uniform buffers. */\n getResourceBindings(): Partial<TBindings> {\n const resourceBindings = {} as Partial<TBindings>;\n\n for (const [name, binding] of Object.entries(this.bindings)) {\n if (!getModuleNameFromUniformBinding(name)) {\n (resourceBindings as Record<string, MaterialBinding>)[name] = binding;\n }\n }\n\n return resourceBindings;\n }\n\n /**\n * Returns resolved bindings, including internal uniform buffers and ready texture sources.\n * @param shaderLayout Reflected bindings used to select copied or external texture resolution.\n */\n getBindings(\n shaderLayout: AnyShaderLayout = {bindings: []}\n ): Partial<{[K in keyof TBindings]: Binding}> & Record<string, Binding> {\n this._syncDynamicResourceGenerations();\n\n const validBindings = {} as Partial<{[K in keyof TBindings]: Binding}> &\n Record<string, Binding>;\n const validBindingsMap = validBindings as Record<string, Binding>;\n for (const [name, binding] of Object.entries(this.bindings)) {\n if (isTextureBindingSource(binding)) {\n const bindingLayout = getTextureBindingLayout(shaderLayout, name, {\n fallbackGroup: MATERIAL_BIND_GROUP\n });\n const resolvedBinding = bindingLayout ? binding.resolveTextureBinding(bindingLayout) : null;\n if (resolvedBinding) {\n validBindingsMap[name] = resolvedBinding;\n }\n } else if (binding instanceof DynamicBuffer) {\n validBindingsMap[name] = binding.buffer;\n } else if (isBufferRangeBinding(binding)) {\n validBindingsMap[name] = resolveBufferRangeBinding(binding);\n } else {\n validBindingsMap[name] = binding;\n }\n }\n\n this._syncDynamicResourceGenerations();\n return validBindings;\n }\n\n /**\n * Packages resolved material bindings into logical bind group `3`.\n * @param shaderLayout Reflected bindings used to select copied or external texture resolution.\n */\n getBindingsByGroup(shaderLayout: AnyShaderLayout = {bindings: []}): BindingsByGroup {\n return this.factory.getBindingsByGroup(this.getBindings(shaderLayout));\n }\n\n /** Returns the stable bind-group cache token for the requested bind group. */\n getBindGroupCacheKey(group: number): object | null {\n this._syncDynamicResourceGenerations();\n return group === MATERIAL_BIND_GROUP ? this._bindGroupCacheToken : null;\n }\n\n /** Returns the latest update timestamp across material-owned resources. */\n getBindingsUpdateTimestamp(): number {\n let timestamp = 0;\n for (const binding of Object.values(this.bindings)) {\n if (binding instanceof TextureView) {\n timestamp = Math.max(timestamp, binding.texture.updateTimestamp);\n } else if (\n binding instanceof Buffer ||\n binding instanceof Texture ||\n binding instanceof ExternalTexture\n ) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (binding instanceof DynamicBuffer) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (isTextureBindingSource(binding)) {\n timestamp = binding.isReady ? Math.max(timestamp, binding.updateTimestamp) : Infinity;\n } else if (isBufferRangeBinding(binding)) {\n timestamp = Math.max(\n timestamp,\n binding.buffer instanceof DynamicBuffer\n ? binding.buffer.updateTimestamp\n : binding.buffer.updateTimestamp\n );\n }\n }\n return timestamp;\n }\n\n /** Replaces owned resource bindings and invalidates the material cache identity when needed. */\n private _replaceOwnedBindings(bindings: Partial<TBindings>): void {\n const didChange = this._setOwnedBindings(bindings);\n if (didChange) {\n this._bindGroupCacheToken = {};\n }\n }\n\n private _setOwnedBindings(\n bindings: Partial<TBindings> | Record<string, MaterialBinding>\n ): boolean {\n let didChange = false;\n\n for (const [name, binding] of Object.entries(bindings)) {\n if (binding === undefined) {\n continue;\n }\n if (!this.ownsBinding(name)) {\n continue;\n }\n\n if (this.bindings[name] !== binding) {\n this.bindings[name] = binding;\n didChange = true;\n }\n }\n\n return didChange;\n }\n\n /** Invalidates the material bind-group key when deferred binding generations change. */\n private _syncDynamicResourceGenerations(): void {\n const nextGenerations: Record<string, number> = {};\n let didChange = false;\n\n for (const [name, binding] of Object.entries(this.bindings)) {\n const dynamicResourceGeneration = getDynamicResourceGeneration(binding);\n if (dynamicResourceGeneration !== null) {\n nextGenerations[name] = dynamicResourceGeneration;\n if (this._dynamicResourceGenerations[name] !== dynamicResourceGeneration) {\n didChange = true;\n }\n }\n }\n\n if (\n Object.keys(nextGenerations).length !== Object.keys(this._dynamicResourceGenerations).length\n ) {\n didChange = true;\n }\n\n this._dynamicResourceGenerations = nextGenerations;\n if (didChange) {\n this._bindGroupCacheToken = {};\n }\n }\n}\n\n/**\n * Returns the generation tracked for one deferred material binding.\n * @param binding Material binding candidate.\n * @returns Deferred binding generation, or `null` for stable concrete bindings.\n */\nfunction getDynamicResourceGeneration(binding: MaterialBinding): number | null {\n if (isTextureBindingSource(binding)) {\n return binding.generation;\n }\n\n return getDynamicBufferFromBinding(binding)?.generation ?? null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, BindingsByGroup, Device} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport type {TextureBindingSource} from '../dynamic-texture/texture-binding-source';\nimport {ShaderInputs} from '../shader-inputs';\nimport type {Material, MaterialProps} from './material';\nimport {Material as MaterialClass} from './material';\n\ntype MaterialModuleProps = Partial<Record<string, Record<string, unknown>>>;\ntype MaterialBindings = Record<\n string,\n | Binding\n | TextureBindingSource\n | import('../dynamic-buffer/dynamic-buffer').DynamicBuffer\n | import('../dynamic-buffer/dynamic-buffer').DynamicBufferRange\n>;\n\n/** Logical bind-group slot reserved for material-owned bindings. */\nexport const MATERIAL_BIND_GROUP = 3;\n\n/** Construction props for {@link MaterialFactory}. */\nexport type MaterialFactoryProps = {\n /** Shader modules that define the material schema for bind group `3`. */\n modules?: ShaderModule[];\n};\n\n/**\n * Creates typed {@link Material} instances for a stable material binding schema.\n *\n * @example\n * ```ts\n * const pbrFactory = new MaterialFactory<\n * {pbrMaterial: PBRMaterialUniforms},\n * PBRMaterialBindings\n * >(device, {modules: [pbrMaterial]});\n * const pbr = pbrFactory.createMaterial();\n * pbr.setProps({pbrMaterial: {baseColorFactor: [1, 0, 0, 1]}});\n * const pbrVariant = pbr.clone({bindings: {pbr_baseColorSampler: texture}});\n * ```\n *\n * @example\n * ```ts\n * const phongFactory = new MaterialFactory<\n * {phongMaterial: PhongMaterialProps},\n * {}\n * >(device, {modules: [phongMaterial]});\n * const phong = phongFactory.createMaterial();\n * phong.setProps({phongMaterial: {ambient: 0.4, diffuse: 0.7}});\n * const phongVariant = phong.clone({moduleProps: {phongMaterial: {shininess: 64}}});\n * ```\n *\n * @example\n * ```ts\n * const gouraudFactory = new MaterialFactory<\n * {gouraudMaterial: GouraudMaterialProps},\n * {}\n * >(device, {modules: [gouraudMaterial]});\n * const gouraud = gouraudFactory.createMaterial();\n * gouraud.setProps({gouraudMaterial: {ambient: 0.25}});\n * const gouraudVariant = gouraud.clone({moduleProps: {gouraudMaterial: {diffuse: 0.8}}});\n * ```\n */\nexport class MaterialFactory<\n TModuleProps extends MaterialModuleProps = MaterialModuleProps,\n TBindings extends MaterialBindings = MaterialBindings\n> {\n /** Device that creates materials for this schema. */\n readonly device: Device;\n /** Shader modules that define the material schema. */\n readonly modules: ShaderModule[];\n\n private _materialBindingNames: Set<string>;\n private _materialModuleNames: Set<string>;\n\n constructor(device: Device, props: MaterialFactoryProps = {}) {\n this.device = device;\n this.modules = props.modules || [];\n\n const shaderInputs = new ShaderInputs(\n Object.fromEntries(this.modules.map(module => [module.name, module]))\n );\n this._materialBindingNames = getMaterialBindingNames(shaderInputs);\n this._materialModuleNames = getMaterialModuleNames(shaderInputs);\n }\n\n /** Creates one typed material instance for this factory's schema. */\n createMaterial(\n props: Omit<MaterialProps<TModuleProps, TBindings>, 'factory' | 'modules'> = {}\n ): Material<TModuleProps, TBindings> {\n return new MaterialClass<TModuleProps, TBindings>(this.device, {\n ...props,\n factory: this\n });\n }\n\n /** Returns the logical material-owned resource binding names. */\n getBindingNames(): string[] {\n return Array.from(this._materialBindingNames);\n }\n\n /** Returns `true` when the supplied binding belongs to this material schema. */\n ownsBinding(bindingName: string): boolean {\n if (this._materialBindingNames.has(bindingName)) {\n return true;\n }\n\n const aliasedModuleName = getModuleNameFromUniformBinding(bindingName);\n return aliasedModuleName ? this._materialModuleNames.has(aliasedModuleName) : false;\n }\n\n /** Returns `true` when the supplied shader module is owned by this material schema. */\n ownsModule(moduleName: string): boolean {\n return this._materialModuleNames.has(moduleName);\n }\n\n /** Packages resolved material bindings into bind group `3`. */\n getBindingsByGroup(\n bindings: Partial<{[K in keyof TBindings]: Binding}> & Record<string, Binding>\n ): BindingsByGroup {\n return Object.keys(bindings).length > 0 ? {[MATERIAL_BIND_GROUP]: bindings} : {};\n }\n}\n\n/** Returns the module name corresponding to an auto-generated `*Uniforms` binding. */\nexport function getModuleNameFromUniformBinding(bindingName: string): string | null {\n return bindingName.endsWith('Uniforms') ? bindingName.slice(0, -'Uniforms'.length) : null;\n}\n\nfunction getMaterialBindingNames(shaderInputs: ShaderInputs): Set<string> {\n const bindingNames = new Set<string>();\n\n for (const module of Object.values(shaderInputs.modules)) {\n for (const binding of module.bindingLayout || []) {\n if (binding.group === MATERIAL_BIND_GROUP) {\n bindingNames.add(binding.name);\n }\n }\n }\n\n return bindingNames;\n}\n\nfunction getMaterialModuleNames(shaderInputs: ShaderInputs): Set<string> {\n const moduleNames = new Set<string>();\n\n for (const module of Object.values(shaderInputs.modules)) {\n if (\n module.name &&\n module.bindingLayout?.some(\n binding => binding.group === MATERIAL_BIND_GROUP && binding.name === module.name\n )\n ) {\n moduleNames.add(module.name);\n }\n }\n\n return moduleNames;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Buffer, BufferRange, TransformFeedback, RenderPassProps} from '@luma.gl/core';\nimport {getPassthroughFS} from '@luma.gl/shadertools';\nimport {Model} from '../model/model';\nimport type {ModelProps} from '../model/model';\n\nconst GL_INTERLEAVED_ATTRIBS = 0x8c8c;\nconst GL_SEPARATE_ATTRIBS = 0x8c8d;\n\n/**\n * Properties for creating a {@link BufferTransform}\n * @note Only works under WebGL2.\n */\nexport type BufferTransformProps = Omit<ModelProps, 'fs'> & {\n /** Optional fragment shader - normally not used in transforms */\n fs?: ModelProps['fs']; // override as optional\n /** bufferMode when binding varyings\n * https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/transformFeedbackVaryings\n */\n feedbackBufferMode?: 'interleaved' | 'separate';\n /** A list of named outputs corresponding to shader declarations (varyings in WebGL) */\n outputs?: string[];\n /** @deprecated Use run({outputBuffers}) instead - Map of output buffers that the shaders will write results of computations to */\n feedbackBuffers?: Record<string, Buffer | BufferRange>;\n};\n\n/**\n * Manages a WebGL program (pipeline) for buffer\u2192buffer transforms.\n * @note Only works under WebGL2.\n */\nexport class BufferTransform {\n readonly device: Device;\n readonly model: Model;\n readonly transformFeedback: TransformFeedback;\n\n static defaultProps: Required<BufferTransformProps> = {\n ...Model.defaultProps,\n feedbackBufferMode: 'separate',\n outputs: undefined!,\n feedbackBuffers: undefined!\n };\n\n static isSupported(device: Device): boolean {\n return device?.info?.type === 'webgl';\n }\n\n constructor(device: Device, props: BufferTransformProps = BufferTransform.defaultProps) {\n if (!BufferTransform.isSupported(device)) {\n throw new Error('BufferTransform not yet implemented on WebGPU');\n }\n\n this.device = device;\n\n this.model = new Model(this.device, {\n id: props.id || 'buffer-transform-model',\n fs: props.fs || getPassthroughFS(),\n topology: props.topology || 'point-list',\n varyings: props.outputs || props.varyings,\n ...props,\n bufferMode:\n props.bufferMode ||\n (props.feedbackBufferMode === 'interleaved' ? GL_INTERLEAVED_ATTRIBS : GL_SEPARATE_ATTRIBS)\n });\n\n this.transformFeedback = this.device.createTransformFeedback({\n layout: this.model.pipeline.shaderLayout,\n // @ts-expect-error TODO\n buffers: props.feedbackBuffers\n });\n\n this.model.setTransformFeedback(this.transformFeedback);\n }\n\n /** Destroy owned resources. */\n destroy(): void {\n if (this.model) {\n this.model.destroy();\n }\n }\n\n /** @deprecated Use {@link destroy}. */\n delete(): void {\n this.destroy();\n }\n\n /** Run one transform loop. */\n run(\n options?: RenderPassProps & {\n inputBuffers?: Record<string, Buffer>;\n outputBuffers?: Record<string, Buffer | BufferRange>;\n }\n ): void {\n if (options?.inputBuffers) {\n this.model.setAttributes(options.inputBuffers);\n }\n if (options?.outputBuffers) {\n this.transformFeedback.setBuffers(options.outputBuffers);\n }\n const renderPass = this.device.beginRenderPass({discard: true, ...options});\n this.model.draw(renderPass);\n renderPass.end();\n }\n\n // DEPRECATED METHODS\n\n /** @deprecated App knows what buffers it is passing in - Returns the {@link Buffer} or {@link BufferRange} for given varying name. */\n getBuffer(varyingName: string): Buffer | BufferRange | null {\n return this.transformFeedback.getBuffer(varyingName);\n }\n\n /** @deprecated App knows what buffers it is passing in - Reads the {@link Buffer} or {@link BufferRange} for given varying name. */\n readAsync(varyingName: string): Promise<Uint8Array> {\n const result = this.getBuffer(varyingName);\n if (!result) {\n throw new Error('BufferTransform#getBuffer');\n }\n if (result instanceof Buffer) {\n return result.readAsync();\n }\n const {buffer, byteOffset = 0, byteLength = buffer.byteLength} = result;\n return buffer.readAsync(byteOffset, byteLength);\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Buffer, Device, Framebuffer, RenderPassProps, Sampler, Texture} from '@luma.gl/core';\nimport {getPassthroughFS} from '@luma.gl/shadertools';\nimport {Model, ModelProps} from '../model/model';\nimport {uid} from '../utils/uid';\n\n/**\n * Properties for creating a {@link TextureTransform}\n */\nexport type TextureTransformProps = Omit<ModelProps, 'fs'> & {\n fs?: ModelProps['fs']; // override as optional\n /** @deprecated TODO(donmccurdy): Needed? */\n inject?: Record<string, string>;\n /** @deprecated TODO(donmccurdy): Needed? */\n framebuffer?: Framebuffer;\n /** @deprecated TODO(donmccurdy): Model already handles this? */\n sourceBuffers?: Record<string, Buffer>;\n /** @deprecated TODO(donmccurdy): Model already handles this? */\n sourceTextures?: Record<string, Texture>;\n targetTexture: Texture;\n targetTextureChannels: 1 | 2 | 3 | 4;\n targetTextureVarying: string;\n};\n\ntype TextureBinding = {\n sourceBuffers: Record<string, Buffer>;\n sourceTextures: Record<string, Texture>;\n targetTexture: Texture;\n framebuffer?: Framebuffer;\n};\n\nconst FS_OUTPUT_VARIABLE = 'transform_output';\n\n/**\n * Creates a pipeline for texture\u2192texture transforms.\n * @deprecated\n */\nexport class TextureTransform {\n readonly device: Device;\n readonly model: Model;\n readonly sampler: Sampler;\n\n currentIndex = 0;\n samplerTextureMap: Record<string, any> | null = null;\n bindings: TextureBinding[] = []; // each element is an object : {sourceTextures, targetTexture, framebuffer}\n resources: Record<string, any> = {}; // resources to be deleted\n\n constructor(device: Device, props: TextureTransformProps) {\n this.device = device;\n\n // For precise picking of element IDs.\n this.sampler = device.createSampler({\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n minFilter: 'nearest',\n magFilter: 'nearest',\n mipmapFilter: 'nearest'\n });\n\n this.model = new Model(this.device, {\n id: props.id || uid('texture-transform-model'),\n fs:\n props.fs ||\n getPassthroughFS({\n input: props.targetTextureVarying,\n inputChannels: props.targetTextureChannels,\n output: FS_OUTPUT_VARIABLE\n }),\n vertexCount: props.vertexCount, // TODO(donmccurdy): Naming?\n ...props\n });\n\n this._initialize(props);\n Object.seal(this);\n }\n\n // Delete owned resources.\n destroy(): void {\n this.model.destroy();\n for (const binding of this.bindings) {\n binding.framebuffer?.destroy();\n }\n }\n\n /** @deprecated Use {@link destroy}. */\n delete(): void {\n this.destroy();\n }\n\n run(options?: RenderPassProps): void {\n const {framebuffer} = this.bindings[this.currentIndex];\n const renderPass = this.device.beginRenderPass({framebuffer, ...options});\n this.model.draw(renderPass);\n renderPass.end();\n this.device.submit();\n }\n\n getTargetTexture(): Texture {\n const {targetTexture} = this.bindings[this.currentIndex];\n return targetTexture;\n }\n\n getFramebuffer(): Framebuffer | undefined {\n const currentResources = this.bindings[this.currentIndex];\n return currentResources.framebuffer;\n }\n\n // Private\n\n _initialize(props: TextureTransformProps): void {\n this._updateBindings(props);\n }\n\n _updateBindings(props: TextureTransformProps) {\n this.bindings[this.currentIndex] = this._updateBinding(this.bindings[this.currentIndex], props);\n }\n\n _updateBinding(\n binding: TextureBinding,\n {sourceBuffers, sourceTextures, targetTexture}: TextureTransformProps\n ): TextureBinding {\n if (!binding) {\n binding = {\n sourceBuffers: {},\n sourceTextures: {},\n // @ts-expect-error\n targetTexture: null\n };\n }\n Object.assign(binding.sourceTextures, sourceTextures);\n Object.assign(binding.sourceBuffers, sourceBuffers);\n if (targetTexture) {\n binding.targetTexture = targetTexture;\n const {width, height} = targetTexture;\n // TODO(donmccurdy): When is this called, and is this expected?\n if (binding.framebuffer) {\n binding.framebuffer.destroy();\n }\n binding.framebuffer = this.device.createFramebuffer({\n id: 'transform-framebuffer',\n width,\n height,\n colorAttachments: [targetTexture]\n });\n binding.framebuffer.resize({width, height});\n }\n return binding;\n }\n\n // set texture filtering parameters on source textures.\n _setSourceTextureParameters(): void {\n const index = this.currentIndex;\n const {sourceTextures} = this.bindings[index];\n for (const name in sourceTextures) {\n sourceTextures[name].sampler = this.sampler;\n }\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// ClipSpace\nimport {Device} from '@luma.gl/core';\nimport {Model, ModelProps} from '../model/model';\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\nconst CLIPSPACE_VERTEX_SHADER_WGSL = /* wgsl */ `\\\nstruct VertexInputs {\n @location(0) clipSpacePositions: vec2<f32>,\n @location(1) texCoords: vec2<f32>,\n @location(2) coordinates: vec2<f32>\n}\n\nstruct FragmentInputs {\n @builtin(position) Position : vec4<f32>,\n @location(0) position : vec2<f32>,\n @location(1) coordinate : vec2<f32>,\n @location(2) uv : vec2<f32>\n};\n\n@vertex\nfn vertexMain(inputs: VertexInputs) -> FragmentInputs {\n var outputs: FragmentInputs;\n outputs.Position = vec4(inputs.clipSpacePositions, 0., 1.);\n outputs.position = inputs.clipSpacePositions;\n outputs.coordinate = inputs.coordinates;\n outputs.uv = inputs.texCoords;\n return outputs;\n}\n`;\n\nconst CLIPSPACE_VERTEX_SHADER = /* glsl */ `\\\n#version 300 es\nin vec2 clipSpacePositions;\nin vec2 texCoords;\nin vec2 coordinates;\n\nout vec2 position;\nout vec2 coordinate;\nout vec2 uv;\n\nvoid main(void) {\n gl_Position = vec4(clipSpacePositions, 0., 1.);\n position = clipSpacePositions;\n coordinate = coordinates;\n uv = texCoords;\n}\n`;\n\n/* eslint-disable indent, no-multi-spaces */\nconst POSITIONS = [-1, -1, 1, -1, -1, 1, 1, 1];\n\n/** Props for ClipSpace */\nexport type ClipSpaceProps = Omit<ModelProps, 'vs' | 'vertexCount' | 'geometry'>;\n\n/**\n * A flat geometry that covers the \"visible area\" that the GPU renders.\n */\nexport class ClipSpace extends Model {\n constructor(device: Device, props: ClipSpaceProps) {\n const TEX_COORDS = POSITIONS.map(coord => (coord === -1 ? 0 : coord));\n\n // For WGSL we need to append the supplied fragment shader to the default vertex shader source\n if (props.source) {\n props = {...props, source: `${CLIPSPACE_VERTEX_SHADER_WGSL}\\n${props.source}`};\n }\n\n super(device, {\n id: props.id || uid('clip-space'),\n ...props,\n vs: CLIPSPACE_VERTEX_SHADER,\n vertexCount: 4,\n geometry: new Geometry({\n topology: 'triangle-strip',\n vertexCount: 4,\n attributes: {\n clipSpacePositions: {size: 2, value: new Float32Array(POSITIONS)},\n texCoords: {size: 2, value: new Float32Array(TEX_COORDS)},\n coordinates: {size: 2, value: new Float32Array(TEX_COORDS)}\n }\n })\n });\n }\n}\n", "// luma.gl, MIT license\n// Copyright (c) vis.gl contributors\n\nimport type {\n TextureProps,\n SamplerProps,\n TextureView,\n Device,\n TextureFormat,\n TextureReadOptions\n} from '@luma.gl/core';\n\nimport {Buffer, Texture, Sampler, log} from '@luma.gl/core';\n\n// import {loadImageBitmap} from '../application-utils/load-file';\nimport {uid} from '../utils/uid';\nimport {\n // cube constants\n type TextureCubeFace,\n TEXTURE_CUBE_FACE_MAP,\n // texture slice/mip data types\n type TextureSubresource,\n // props (dimension + data)\n type TextureDataProps,\n type TextureDataAsyncProps,\n // combined data for different texture types\n type Texture1DData,\n type Texture2DData,\n type Texture3DData,\n type TextureArrayData,\n type TextureCubeArrayData,\n type TextureCubeData,\n // Helpers\n getTextureSizeFromData,\n resolveTextureImageFormat,\n getTexture1DSubresources,\n getTexture2DSubresources,\n getTexture3DSubresources,\n getTextureCubeSubresources,\n getTextureArraySubresources,\n getTextureCubeArraySubresources\n} from './texture-data';\nimport type {TextureBindingLayout, TextureBindingSource} from './texture-binding-source';\n\n/**\n * Properties for a dynamic texture\n */\nexport type DynamicTextureProps = Omit<TextureProps, 'data' | 'mipLevels' | 'width' | 'height'> &\n TextureDataAsyncProps & {\n /** Generate mipmaps after creating textures and setting data */\n mipmaps?: boolean;\n /** nipLevels can be set to 'auto' to generate max number of mipLevels */\n mipLevels?: number | 'auto';\n /** Width - can be auto-calculated when initializing from ExternalImage */\n width?: number;\n /** Height - can be auto-calculated when initializing from ExternalImage */\n height?: number;\n };\n\n/**\n * Dynamic Textures\n *\n * - Mipmaps - DynamicTexture can generate mipmaps for textures (WebGPU does not provide built-in mipmap generation).\n *\n * - Texture initialization and updates - complex textures (2d array textures, cube textures, 3d textures) need multiple images\n * `DynamicTexture` provides an API that makes it easy to provide the required data.\n *\n * - Texture resizing - Textures are immutable in WebGPU, meaning that they cannot be resized after creation.\n * DynamicTexture provides a `resize()` method that internally creates a new texture with the same parameters\n * but a different size.\n *\n * - Async image data initialization - It is often very convenient to be able to initialize textures with promises\n * returned by image or data loading functions, as it allows a callback-free linear style of programming.\n *\n * @note GPU Textures are quite complex objects, with many subresources and modes of usage.\n * The `DynamicTexture` class allows luma.gl to provide some support for working with textures\n * without accumulating excessive complexity in the core Texture class which is designed as an immutable nature of GPU resource.\n */\nexport class DynamicTexture implements TextureBindingSource {\n readonly device: Device;\n readonly id: string;\n\n /** Props with defaults resolved (except `data` which is processed separately) */\n props: Readonly<Required<DynamicTextureProps>>;\n\n /** Created resources */\n private _texture: Texture | null = null;\n private _sampler: Sampler | null = null;\n private _view: TextureView | null = null;\n\n /** Ready when GPU texture has been created and data (if any) uploaded */\n readonly ready: Promise<Texture>;\n isReady = false;\n destroyed = false;\n /** Monotonic version that increments whenever texture, view, or sampler identity changes. */\n generation = 0;\n /** Last update timestamp for texture content, readiness, or identity changes. */\n updateTimestamp: number;\n\n private resolveReady: (t: Texture) => void = () => {};\n private rejectReady: (error: Error) => void = () => {};\n\n get texture(): Texture {\n if (!this._texture) throw new Error('Texture not initialized yet');\n return this._texture;\n }\n get sampler(): Sampler {\n if (!this._sampler) throw new Error('Sampler not initialized yet');\n return this._sampler;\n }\n get view(): TextureView {\n if (!this._view) throw new Error('View not initialized yet');\n return this._view;\n }\n\n get [Symbol.toStringTag]() {\n return 'DynamicTexture';\n }\n toString(): string {\n const width = this._texture?.width ?? this.props.width ?? '?';\n const height = this._texture?.height ?? this.props.height ?? '?';\n return `DynamicTexture:\"${this.id}\":${width}x${height}px:(${this.isReady ? 'ready' : 'loading...'})`;\n }\n\n /**\n * Resolves this ready dynamic texture as an ordinary copied texture binding.\n * @param _bindingLayout Reflected texture-like shader slot; DynamicTexture always resolves a copied texture.\n * @returns The copied texture, or `null` while the source is not ready.\n */\n resolveTextureBinding(_bindingLayout: TextureBindingLayout): Texture | null {\n return this.isReady ? this.texture : null;\n }\n\n constructor(device: Device, props: DynamicTextureProps) {\n this.device = device;\n\n const id = uid('dynamic-texture');\n // NOTE: We avoid holding on to data to make sure it can be garbage collected.\n const originalPropsWithAsyncData = props;\n this.props = {...DynamicTexture.defaultProps, id, ...props, data: null};\n this.id = this.props.id;\n\n this.ready = new Promise<Texture>((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n this.updateTimestamp = this.device.incrementTimestamp();\n\n this.initAsync(originalPropsWithAsyncData);\n }\n\n /** @note Fire and forget; caller can await `ready` */\n async initAsync(originalPropsWithAsyncData: DynamicTextureProps): Promise<void> {\n try {\n // TODO - Accept URL string for 2D: turn into ExternalImage promise\n // const dataProps =\n // typeof props.data === 'string' && (props.dimension ?? '2d') === '2d'\n // ? ({dimension: '2d', data: loadImageBitmap(props.data)} as const)\n // : {};\n\n const propsWithSyncData = await this._loadAllData(originalPropsWithAsyncData);\n this._checkNotDestroyed();\n const subresources = propsWithSyncData.data\n ? getTextureSubresources({\n ...propsWithSyncData,\n width: originalPropsWithAsyncData.width,\n height: originalPropsWithAsyncData.height,\n format: originalPropsWithAsyncData.format\n })\n : [];\n const userProvidedFormat =\n 'format' in originalPropsWithAsyncData && originalPropsWithAsyncData.format !== undefined;\n const userProvidedUsage =\n 'usage' in originalPropsWithAsyncData && originalPropsWithAsyncData.usage !== undefined;\n\n // Deduce size when not explicitly provided\n // TODO - what about depth?\n const deduceSize = (): {width: number; height: number} => {\n if (this.props.width && this.props.height) {\n return {width: this.props.width, height: this.props.height};\n }\n\n const size = getTextureSizeFromData(propsWithSyncData);\n if (size) {\n return size;\n }\n\n return {width: this.props.width || 1, height: this.props.height || 1};\n };\n\n const size = deduceSize();\n if (!size || size.width <= 0 || size.height <= 0) {\n throw new Error(`${this} size could not be determined or was zero`);\n }\n\n // Normalize caller-provided subresources into one validated mip chain description.\n const textureData = analyzeTextureSubresources(this.device, subresources, size, {\n format: userProvidedFormat ? originalPropsWithAsyncData.format : undefined\n });\n const resolvedFormat = textureData.format ?? this.props.format;\n\n // Create a minimal TextureProps and validate via `satisfies`\n const baseTextureProps = {\n ...this.props,\n ...size,\n format: resolvedFormat,\n mipLevels: 1, // temporary; updated below\n data: undefined\n } satisfies TextureProps;\n\n if (this.device.isTextureFormatCompressed(resolvedFormat) && !userProvidedUsage) {\n baseTextureProps.usage = Texture.SAMPLE | Texture.COPY_DST;\n }\n\n // Explicit mip arrays take ownership of the mip chain; otherwise we may auto-generate it.\n const shouldGenerateMipmaps =\n this.props.mipmaps &&\n !textureData.hasExplicitMipChain &&\n !this.device.isTextureFormatCompressed(resolvedFormat);\n\n if (this.device.type === 'webgpu' && shouldGenerateMipmaps) {\n const requiredUsage =\n this.props.dimension === '3d'\n ? Texture.SAMPLE | Texture.STORAGE | Texture.COPY_DST | Texture.COPY_SRC\n : Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST | Texture.COPY_SRC;\n baseTextureProps.usage |= requiredUsage;\n }\n\n // Compute mip levels (auto clamps to max)\n const maxMips = this.device.getMipLevelCount(baseTextureProps.width, baseTextureProps.height);\n const desired = textureData.hasExplicitMipChain\n ? textureData.mipLevels\n : this.props.mipLevels === 'auto'\n ? maxMips\n : Math.max(1, Math.min(maxMips, this.props.mipLevels ?? 1));\n\n const finalTextureProps: TextureProps = {...baseTextureProps, mipLevels: desired};\n\n this._texture = this.device.createTexture(finalTextureProps);\n this._sampler = this.texture.sampler;\n this._view = this.texture.view;\n this._touchGeneration();\n\n // Upload data if provided\n if (textureData.subresources.length) {\n this._setTextureSubresources(textureData.subresources);\n }\n\n if (this.props.mipmaps && !textureData.hasExplicitMipChain && !shouldGenerateMipmaps) {\n log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)();\n }\n\n if (shouldGenerateMipmaps) {\n this.generateMipmaps();\n }\n\n this.isReady = true;\n this.resolveReady(this.texture);\n\n log.info(1, `${this} created`)();\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.rejectReady(err);\n }\n }\n\n destroy(): void {\n if (this._texture) {\n this._texture.destroy();\n this._texture = null;\n this._sampler = null;\n this._view = null;\n }\n this.isReady = false;\n this.destroyed = true;\n }\n\n generateMipmaps(): void {\n if (this.device.type === 'webgl') {\n this.texture.generateMipmapsWebGL();\n this._touch();\n } else if (this.device.type === 'webgpu') {\n this.device.generateMipmapsWebGPU(this.texture);\n this._touch();\n } else {\n log.warn(`${this} mipmaps not supported on ${this.device.type}`);\n }\n }\n\n /** Set sampler or create one from props */\n setSampler(sampler: Sampler | SamplerProps = {}): void {\n this._checkReady();\n const s = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);\n this.texture.setSampler(s);\n this._sampler = s;\n this._touchGeneration();\n }\n\n /**\n * Copies texture contents into a GPU buffer and waits until the copy is complete.\n * The caller owns the returned buffer and must destroy it when finished.\n */\n async readBuffer(options: TextureReadOptions = {}): Promise<Buffer> {\n if (!this.isReady) {\n await this.ready;\n }\n\n const width = options.width ?? this.texture.width;\n const height = options.height ?? this.texture.height;\n const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth;\n const layout = this.texture.computeMemoryLayout({width, height, depthOrArrayLayers});\n\n const buffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n\n this.texture.readBuffer(\n {\n ...options,\n width,\n height,\n depthOrArrayLayers\n },\n buffer\n );\n\n const fence = this.device.createFence();\n await fence.signaled;\n fence.destroy();\n\n return buffer;\n }\n\n /** Reads texture contents back to CPU memory. */\n async readAsync(options: TextureReadOptions = {}): Promise<ArrayBuffer> {\n if (!this.isReady) {\n await this.ready;\n }\n\n const width = options.width ?? this.texture.width;\n const height = options.height ?? this.texture.height;\n const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth;\n const layout = this.texture.computeMemoryLayout({width, height, depthOrArrayLayers});\n\n const buffer = await this.readBuffer(options);\n const data = await buffer.readAsync(0, layout.byteLength);\n buffer.destroy();\n return data.buffer instanceof ArrayBuffer ? data.buffer : data.slice().buffer;\n }\n\n /**\n * Resize by cloning the underlying immutable texture.\n * Does not copy contents; caller may need to re-upload and/or regenerate mips.\n */\n resize(size: {width: number; height: number}): boolean {\n this._checkReady();\n\n if (size.width === this.texture.width && size.height === this.texture.height) {\n return false;\n }\n const prev = this.texture;\n this._texture = prev.clone(size);\n this._sampler = this.texture.sampler;\n this._view = this.texture.view;\n\n prev.destroy();\n this._touchGeneration();\n log.info(`${this} resized`);\n return true;\n }\n\n /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\n getCubeFaceIndex(face: TextureCubeFace): number {\n const index = TEXTURE_CUBE_FACE_MAP[face];\n if (index === undefined) throw new Error(`Invalid cube face: ${face}`);\n return index;\n }\n\n /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\n getCubeArrayFaceIndex(cubeIndex: number, face: TextureCubeFace): number {\n return 6 * cubeIndex + this.getCubeFaceIndex(face);\n }\n\n /** @note experimental: Set multiple mip levels (1D) */\n setTexture1DData(data: Texture1DData): void {\n this._checkReady();\n if (this.texture.props.dimension !== '1d') {\n throw new Error(`${this} is not 1d`);\n }\n const subresources = getTexture1DSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */\n setTexture2DData(lodData: Texture2DData, z: number = 0): void {\n this._checkReady();\n if (this.texture.props.dimension !== '2d') {\n throw new Error(`${this} is not 2d`);\n }\n\n const subresources = getTexture2DSubresources(z, lodData);\n this._setTextureSubresources(subresources);\n }\n\n /** 3D: multiple depth slices, each may carry multiple mip levels */\n setTexture3DData(data: Texture3DData): void {\n if (this.texture.props.dimension !== '3d') {\n throw new Error(`${this} is not 3d`);\n }\n const subresources = getTexture3DSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** 2D array: multiple layers, each may carry multiple mip levels */\n setTextureArrayData(data: TextureArrayData): void {\n if (this.texture.props.dimension !== '2d-array') {\n throw new Error(`${this} is not 2d-array`);\n }\n const subresources = getTextureArraySubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Cube: 6 faces, each may carry multiple mip levels */\n setTextureCubeData(data: TextureCubeData): void {\n if (this.texture.props.dimension !== 'cube') {\n throw new Error(`${this} is not cube`);\n }\n const subresources = getTextureCubeSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Cube array: multiple cubes (faces\u00D7layers), each face may carry multiple mips */\n setTextureCubeArrayData(data: TextureCubeArrayData): void {\n if (this.texture.props.dimension !== 'cube-array') {\n throw new Error(`${this} is not cube-array`);\n }\n const subresources = getTextureCubeArraySubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Sets multiple mip levels on different `z` slices (depth/array index) */\n private _setTextureSubresources(subresources: TextureSubresource[]): void {\n // If user supplied multiple mip levels, warn if auto-mips also requested\n // if (lodArray.length > 1 && this.props.mipmaps !== false) {\n // log.warn(\n // `Texture ${this.id}: provided multiple LODs and also requested mipmap generation.`\n // )();\n // }\n\n for (const subresource of subresources) {\n const {z, mipLevel} = subresource;\n switch (subresource.type) {\n case 'external-image':\n const {image, flipY} = subresource;\n this.texture.copyExternalImage({image, z, mipLevel, flipY});\n break;\n case 'texture-data':\n const {data, textureFormat} = subresource;\n if (textureFormat && textureFormat !== this.texture.format) {\n throw new Error(\n `${this} mip level ${mipLevel} uses format \"${textureFormat}\" but texture format is \"${this.texture.format}\"`\n );\n }\n this.texture.writeData(data.data, {\n x: 0,\n y: 0,\n z,\n width: data.width,\n height: data.height,\n depthOrArrayLayers: 1,\n mipLevel\n });\n break;\n default:\n throw new Error('Unsupported 2D mip-level payload');\n }\n }\n if (subresources.length > 0) {\n this._touch();\n }\n }\n\n // ------------------ helpers ------------------\n\n /** Recursively resolve all promises in data structures */\n private async _loadAllData(props: TextureDataAsyncProps): Promise<TextureDataProps> {\n const syncData = await awaitAllPromises(props.data);\n const dimension = (props.dimension ?? '2d') as TextureDataProps['dimension'];\n return {dimension, data: syncData ?? null} as TextureDataProps;\n }\n\n private _checkNotDestroyed() {\n if (this.destroyed) {\n log.warn(`${this} already destroyed`);\n }\n }\n\n private _checkReady() {\n if (!this.isReady) {\n log.warn(`${this} Cannot perform this operation before ready`);\n }\n }\n\n private _touch(): void {\n this.updateTimestamp = this.device.incrementTimestamp();\n }\n\n private _touchGeneration(): void {\n this.generation++;\n this._touch();\n }\n\n static defaultProps: Required<DynamicTextureProps> = {\n ...Texture.defaultProps,\n dimension: '2d',\n data: null,\n mipmaps: false\n };\n}\n\ntype TextureSubresourceAnalysis = {\n readonly subresources: TextureSubresource[];\n readonly mipLevels: number;\n readonly format?: TextureFormat;\n readonly hasExplicitMipChain: boolean;\n};\n\n// Flatten dimension-specific texture data into one list of uploadable subresources.\nfunction getTextureSubresources(\n props: TextureDataProps & Partial<Pick<TextureProps, 'width' | 'height' | 'format'>>\n): TextureSubresource[] {\n if (!props.data) {\n return [];\n }\n\n const baseLevelSize =\n props.width && props.height ? {width: props.width, height: props.height} : undefined;\n const textureFormat = 'format' in props ? props.format : undefined;\n\n switch (props.dimension) {\n case '1d':\n return getTexture1DSubresources(props.data);\n case '2d':\n return getTexture2DSubresources(0, props.data, baseLevelSize, textureFormat);\n case '3d':\n return getTexture3DSubresources(props.data);\n case '2d-array':\n return getTextureArraySubresources(props.data);\n case 'cube':\n return getTextureCubeSubresources(props.data);\n case 'cube-array':\n return getTextureCubeArraySubresources(props.data);\n default:\n throw new Error(`Unhandled dimension ${(props as TextureDataProps).dimension}`);\n }\n}\n\n// Resolve a consistent texture format and the longest mip chain valid across all slices.\nfunction analyzeTextureSubresources(\n device: Device,\n subresources: TextureSubresource[],\n size: {width: number; height: number},\n options: {format?: TextureFormat}\n): TextureSubresourceAnalysis {\n if (subresources.length === 0) {\n return {\n subresources,\n mipLevels: 1,\n format: options.format,\n hasExplicitMipChain: false\n };\n }\n\n const groupedSubresources = new Map<number, TextureSubresource[]>();\n for (const subresource of subresources) {\n const group = groupedSubresources.get(subresource.z) ?? [];\n group.push(subresource);\n groupedSubresources.set(subresource.z, group);\n }\n\n const hasExplicitMipChain = subresources.some(subresource => subresource.mipLevel > 0);\n let resolvedFormat = options.format;\n let resolvedMipLevels = Number.POSITIVE_INFINITY;\n const validSubresources: TextureSubresource[] = [];\n\n for (const [z, sliceSubresources] of groupedSubresources) {\n // Validate each slice independently, then keep only the mip levels that are valid everywhere.\n const sortedSubresources = [...sliceSubresources].sort(\n (left, right) => left.mipLevel - right.mipLevel\n );\n const baseLevel = sortedSubresources[0];\n if (!baseLevel || baseLevel.mipLevel !== 0) {\n throw new Error(`DynamicTexture: slice ${z} is missing mip level 0`);\n }\n\n const baseSize = getTextureSubresourceSize(device, baseLevel);\n if (baseSize.width !== size.width || baseSize.height !== size.height) {\n throw new Error(\n `DynamicTexture: slice ${z} base level dimensions ${baseSize.width}x${baseSize.height} do not match expected ${size.width}x${size.height}`\n );\n }\n\n const baseFormat = getTextureSubresourceFormat(baseLevel);\n if (baseFormat) {\n if (resolvedFormat && resolvedFormat !== baseFormat) {\n throw new Error(\n `DynamicTexture: slice ${z} base level format \"${baseFormat}\" does not match texture format \"${resolvedFormat}\"`\n );\n }\n resolvedFormat = baseFormat;\n }\n\n const mipLevelLimit =\n resolvedFormat && device.isTextureFormatCompressed(resolvedFormat)\n ? // Block-compressed formats cannot have mips smaller than a single compression block.\n getMaxCompressedMipLevels(device, baseSize.width, baseSize.height, resolvedFormat)\n : device.getMipLevelCount(baseSize.width, baseSize.height);\n\n let validMipLevelsForSlice = 0;\n for (\n let expectedMipLevel = 0;\n expectedMipLevel < sortedSubresources.length;\n expectedMipLevel++\n ) {\n const subresource = sortedSubresources[expectedMipLevel];\n // Stop at the first gap so callers can provide extra trailing data without breaking creation.\n if (!subresource || subresource.mipLevel !== expectedMipLevel) {\n break;\n }\n if (expectedMipLevel >= mipLevelLimit) {\n break;\n }\n\n const subresourceSize = getTextureSubresourceSize(device, subresource);\n const expectedWidth = Math.max(1, baseSize.width >> expectedMipLevel);\n const expectedHeight = Math.max(1, baseSize.height >> expectedMipLevel);\n if (subresourceSize.width !== expectedWidth || subresourceSize.height !== expectedHeight) {\n break;\n }\n\n const subresourceFormat = getTextureSubresourceFormat(subresource);\n if (subresourceFormat) {\n if (!resolvedFormat) {\n resolvedFormat = subresourceFormat;\n }\n // Later mip levels must stay on the same format as the validated base level.\n if (subresourceFormat !== resolvedFormat) {\n break;\n }\n }\n\n validMipLevelsForSlice++;\n validSubresources.push(subresource);\n }\n\n resolvedMipLevels = Math.min(resolvedMipLevels, validMipLevelsForSlice);\n }\n\n const mipLevels = Number.isFinite(resolvedMipLevels) ? Math.max(1, resolvedMipLevels) : 1;\n\n return {\n // Keep every slice trimmed to the same mip count so the texture shape stays internally consistent.\n subresources: validSubresources.filter(subresource => subresource.mipLevel < mipLevels),\n mipLevels,\n format: resolvedFormat,\n hasExplicitMipChain\n };\n}\n\n// Read the per-level format using the transitional textureFormat -> format fallback rules.\nfunction getTextureSubresourceFormat(subresource: TextureSubresource): TextureFormat | undefined {\n if (subresource.type !== 'texture-data') {\n return undefined;\n }\n return subresource.textureFormat ?? resolveTextureImageFormat(subresource.data);\n}\n\n// Resolve dimensions from either raw bytes or external-image subresources.\nfunction getTextureSubresourceSize(\n device: Device,\n subresource: TextureSubresource\n): {width: number; height: number} {\n switch (subresource.type) {\n case 'external-image':\n return device.getExternalImageSize(subresource.image);\n case 'texture-data':\n return {width: subresource.data.width, height: subresource.data.height};\n default:\n throw new Error('Unsupported texture subresource');\n }\n}\n\n// Count the mip levels that stay at or above one compression block in each dimension.\nfunction getMaxCompressedMipLevels(\n device: Device,\n baseWidth: number,\n baseHeight: number,\n format: TextureFormat\n): number {\n const {blockWidth = 1, blockHeight = 1} = device.getTextureFormatInfo(format);\n let mipLevels = 1;\n for (let mipLevel = 1; ; mipLevel++) {\n const width = Math.max(1, baseWidth >> mipLevel);\n const height = Math.max(1, baseHeight >> mipLevel);\n if (width < blockWidth || height < blockHeight) {\n break;\n }\n mipLevels++;\n }\n return mipLevels;\n}\n\n// HELPERS\n\n/** Resolve all promises in a nested data structure */\nasync function awaitAllPromises(x: any): Promise<any> {\n x = await x;\n if (Array.isArray(x)) {\n return await Promise.all(x.map(awaitAllPromises));\n }\n if (x && typeof x === 'object' && x.constructor === Object) {\n const object: Record<string, any> = x;\n const values = await Promise.all(Object.values(object).map(awaitAllPromises));\n const keys = Object.keys(object);\n const resolvedObject: Record<string, any> = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObject[keys[i]] = values[i];\n }\n return resolvedObject;\n }\n return x;\n}\n\n// /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */\n// setTexture2DData(lodData: Texture2DData, z: number = 0): void {\n// this._checkReady();\n\n// const lodArray = this._normalizeTexture2DData(lodData);\n\n// // If user supplied multiple mip levels, warn if auto-mips also requested\n// if (lodArray.length > 1 && this.props.mipmaps !== false) {\n// log.warn(\n// `Texture ${this.id}: provided multiple LODs and also requested mipmap generation.`\n// )();\n// }\n\n// for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) {\n// const imageData = lodArray[mipLevel];\n// if (this.device.isExternalImage(imageData)) {\n// this.texture.copyExternalImage({image: imageData, z, mipLevel, flipY: true});\n// } else if (this._isTextureImageData(imageData)) {\n// this.texture.copyImageData({data: imageData.data, z, mipLevel});\n// } else {\n// throw new Error('Unsupported 2D mip-level payload');\n// }\n// }\n// }\n\n// /** Normalize 2D layer payload into an array of mip-level items */\n// private _normalizeTexture2DData(data: Texture2DData): (TextureImageData | ExternalImage)[] {\n// return Array.isArray(data) ? data : [data];\n// }\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray, TextureFormat, ExternalImage} from '@luma.gl/core';\nimport {isExternalImage, getExternalImageSize} from '@luma.gl/core';\n\nexport type TextureImageSource = ExternalImage;\n\n/**\n * One mip level\n * Basic data structure is similar to `ImageData`\n * additional optional fields can describe compressed texture data.\n */\nexport type TextureImageData = {\n /** Preferred WebGPU style format string. */\n textureFormat?: TextureFormat;\n /** WebGPU style format string. Defaults to 'rgba8unorm' */\n format?: TextureFormat;\n /** Typed Array with the bytes of the image. @note beware row byte alignment requirements */\n data: TypedArray;\n /** Width of the image, in pixels, @note beware row byte alignment requirements */\n width: number;\n /** Height of the image, in rows */\n height: number;\n};\n\n/**\n * A single mip-level can be initialized by data or an ImageBitmap etc\n * @note in the WebGPU spec a mip-level is called a subresource\n */\nexport type TextureMipLevelData = TextureImageData | TextureImageSource;\n\n/**\n * Texture data for one image \"slice\" (which can consist of multiple miplevels)\n * Thus data for one slice be a single mip level or an array of miplevels\n * @note in the WebGPU spec each cross-section image in a 3D texture is called a \"slice\",\n * in a array texture each image in the array is called an array \"layer\"\n * luma.gl calls one image in a GPU texture a \"slice\" regardless of context.\n */\nexport type TextureSliceData = TextureMipLevelData | TextureMipLevelData[];\n\n/** Names of cube texture faces */\nexport type TextureCubeFace = '+X' | '-X' | '+Y' | '-Y' | '+Z' | '-Z';\n\n/** Array of cube texture faces. @note: index in array is the face index */\n// biome-ignore format: preserve layout\nexport const TEXTURE_CUBE_FACES = ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] as const satisfies readonly TextureCubeFace[];\n\n/** Map of cube texture face names to face indexes */\n// biome-ignore format: preserve layout\nexport const TEXTURE_CUBE_FACE_MAP = {'+X': 0, '-X': 1, '+Y': 2, '-Y': 3, '+Z': 4, '-Z': 5} as const satisfies Record<TextureCubeFace, number>;\n\n/** @todo - Define what data type is supported for 1D textures. TextureImageData with height = 1 */\nexport type Texture1DData = TextureSliceData;\n\n/** Texture data can be one or more mip levels */\nexport type Texture2DData = TextureSliceData;\n\n/** Texture data accepted when initializing a standalone 2D texture. */\ntype Texture2DDataSource = Texture2DData | TypedArray;\n\n/** 6 face textures */\nexport type TextureCubeData = Record<TextureCubeFace, TextureSliceData>;\n\n/** Array of textures */\nexport type Texture3DData = TextureSliceData[];\n\n/** Array of textures */\nexport type TextureArrayData = TextureSliceData[];\n\n/** Array of 6 face textures */\nexport type TextureCubeArrayData = Record<TextureCubeFace, TextureSliceData>[];\n\ntype TextureData =\n | Texture1DData\n | Texture3DData\n | TextureArrayData\n | TextureCubeArrayData\n | TextureCubeData;\n\n/** Sync data props */\nexport type TextureDataProps =\n | {dimension: '1d'; data: Texture1DData | null}\n | {dimension?: '2d'; data: Texture2DDataSource | null}\n | {dimension: '3d'; data: Texture3DData | null}\n | {dimension: '2d-array'; data: TextureArrayData | null}\n | {dimension: 'cube'; data: TextureCubeData | null}\n | {dimension: 'cube-array'; data: TextureCubeArrayData | null};\n\n/** Async data props */\nexport type TextureDataAsyncProps =\n | {dimension: '1d'; data?: Promise<Texture1DData> | Texture1DData | null}\n | {dimension?: '2d'; data?: Promise<Texture2DDataSource> | Texture2DDataSource | null}\n | {dimension: '3d'; data?: Promise<Texture3DData> | Texture3DData | null}\n | {dimension: '2d-array'; data?: Promise<TextureArrayData> | TextureArrayData | null}\n | {dimension: 'cube'; data?: Promise<TextureCubeData> | TextureCubeData | null}\n | {dimension: 'cube-array'; data?: Promise<TextureCubeArrayData> | TextureCubeArrayData | null};\n\n/** Describes data for one sub resource (one mip level of one slice (depth or array layer)) */\nexport type TextureSubresource = {\n /** slice (depth or array layer)) */\n z: number;\n /** mip level (0 - max mip levels) */\n mipLevel: number;\n} & (\n | {\n type: 'external-image';\n image: ExternalImage;\n /** @deprecated is this an appropriate place for this flag? */\n flipY?: boolean;\n }\n | {\n type: 'texture-data';\n data: TextureImageData;\n textureFormat?: TextureFormat;\n }\n);\n\n/** Check if texture data is a typed array */\nexport function isTextureSliceData(data: TextureData): data is TextureImageData {\n const typedArray = (data as TextureImageData)?.data;\n return ArrayBuffer.isView(typedArray);\n}\n\nexport function getFirstMipLevel(layer: TextureSliceData | null): TextureMipLevelData | null {\n if (!layer) return null;\n return Array.isArray(layer) ? (layer[0] ?? null) : layer;\n}\n\nexport function getTextureSizeFromData(\n props: TextureDataProps\n): {width: number; height: number} | null {\n const {dimension, data} = props;\n if (!data) {\n return null;\n }\n\n switch (dimension) {\n case '1d': {\n const mipLevel = getFirstMipLevel(data);\n if (!mipLevel) return null;\n const {width} = getTextureMipLevelSize(mipLevel);\n return {width, height: 1};\n }\n case '2d': {\n if (ArrayBuffer.isView(data)) return null;\n const mipLevel = getFirstMipLevel(data);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case '3d':\n case '2d-array': {\n if (!Array.isArray(data) || data.length === 0) return null;\n const mipLevel = getFirstMipLevel(data[0]);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case 'cube': {\n const face = (Object.keys(data)[0] as TextureCubeFace) ?? null;\n if (!face) return null;\n const faceData = (data as Record<TextureCubeFace, TextureSliceData>)[face];\n const mipLevel = getFirstMipLevel(faceData);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case 'cube-array': {\n if (!Array.isArray(data) || data.length === 0) return null;\n const firstCube = data[0];\n const face = (Object.keys(firstCube)[0] as TextureCubeFace) ?? null;\n if (!face) return null;\n const mipLevel = getFirstMipLevel(firstCube[face]);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n default:\n return null;\n }\n}\n\nfunction getTextureMipLevelSize(data: TextureMipLevelData): {width: number; height: number} {\n if (isExternalImage(data)) {\n return getExternalImageSize(data);\n }\n if (typeof data === 'object' && 'width' in data && 'height' in data) {\n return {width: data.width, height: data.height};\n }\n throw new Error('Unsupported mip-level data');\n}\n\n/** Type guard: is a mip-level `TextureImageData` (vs ExternalImage or bare typed array) */\nfunction isTextureImageData(data: unknown): data is TextureImageData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'data' in data &&\n 'width' in data &&\n 'height' in data\n );\n}\n\nfunction isTypedArrayMipLevelData(data: unknown): data is TypedArray {\n return ArrayBuffer.isView(data);\n}\n\nexport function resolveTextureImageFormat(data: TextureImageData): TextureFormat | undefined {\n const {textureFormat, format} = data;\n if (textureFormat && format && textureFormat !== format) {\n throw new Error(\n `Conflicting texture formats \"${textureFormat}\" and \"${format}\" provided for the same mip level`\n );\n }\n return textureFormat ?? format;\n}\n\n/** Resolve size for a single mip-level datum */\n// function getTextureMipLevelSizeFromData(data: TextureMipLevelData): {\n// width: number;\n// height: number;\n// } {\n// if (this.device.isExternalImage(data)) {\n// return this.device.getExternalImageSize(data);\n// }\n// if (this.isTextureImageData(data)) {\n// return {width: data.width, height: data.height};\n// }\n// // Fallback (should not happen with current types)\n// throw new Error('Unsupported mip-level data');\n// }\n\n/** Convert cube face label to depth index */\nexport function getCubeFaceIndex(face: TextureCubeFace): number {\n const idx = TEXTURE_CUBE_FACE_MAP[face];\n if (idx === undefined) throw new Error(`Invalid cube face: ${face}`);\n return idx;\n}\n\n/** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\nexport function getCubeArrayFaceIndex(cubeIndex: number, face: TextureCubeFace): number {\n return 6 * cubeIndex + getCubeFaceIndex(face);\n}\n\n// ------------------ Upload helpers ------------------\n\n/** Experimental: Set multiple mip levels (1D) */\nexport function getTexture1DSubresources(data: Texture1DData): TextureSubresource[] {\n // Not supported in WebGL; left explicit\n throw new Error('setTexture1DData not supported in WebGL.');\n // const subresources: TextureSubresource[] = [];\n // return subresources;\n}\n\n/** Normalize 2D layer payload into an array of mip-level items */\nfunction _normalizeTexture2DData(\n data: Texture2DDataSource\n): (TextureImageData | ExternalImage | TypedArray)[] {\n return Array.isArray(data) ? data : [data];\n}\n\n/** Experimental: Set multiple mip levels (2D), optionally at `z` (depth/array index) */\nexport function getTexture2DSubresources(\n slice: number,\n lodData: Texture2DDataSource,\n baseLevelSize?: {width: number; height: number},\n textureFormat?: TextureFormat\n): TextureSubresource[] {\n const lodArray = _normalizeTexture2DData(lodData);\n const z = slice;\n\n const subresources: TextureSubresource[] = [];\n\n for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) {\n const imageData = lodArray[mipLevel];\n if (isExternalImage(imageData)) {\n subresources.push({\n type: 'external-image',\n image: imageData,\n z,\n mipLevel\n });\n } else if (isTextureImageData(imageData)) {\n subresources.push({\n type: 'texture-data',\n data: imageData,\n textureFormat: resolveTextureImageFormat(imageData),\n z,\n mipLevel\n });\n } else if (isTypedArrayMipLevelData(imageData) && baseLevelSize) {\n subresources.push({\n type: 'texture-data',\n data: {\n data: imageData,\n width: Math.max(1, baseLevelSize.width >> mipLevel),\n height: Math.max(1, baseLevelSize.height >> mipLevel),\n ...(textureFormat ? {format: textureFormat} : {})\n },\n textureFormat,\n z,\n mipLevel\n });\n } else {\n throw new Error('Unsupported 2D mip-level payload');\n }\n }\n\n return subresources;\n}\n\n/** 3D: multiple depth slices, each may carry multiple mip levels */\nexport function getTexture3DSubresources(data: Texture3DData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (let depth = 0; depth < data.length; depth++) {\n subresources.push(...getTexture2DSubresources(depth, data[depth]));\n }\n return subresources;\n}\n\n/** 2D array: multiple layers, each may carry multiple mip levels */\nexport function getTextureArraySubresources(data: TextureArrayData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (let layer = 0; layer < data.length; layer++) {\n subresources.push(...getTexture2DSubresources(layer, data[layer]));\n }\n return subresources;\n}\n\n/** Cube: 6 faces, each may carry multiple mip levels */\nexport function getTextureCubeSubresources(data: TextureCubeData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (const [face, faceData] of Object.entries(data) as [TextureCubeFace, TextureSliceData][]) {\n const faceDepth = getCubeFaceIndex(face);\n subresources.push(...getTexture2DSubresources(faceDepth, faceData));\n }\n return subresources;\n}\n\n/** Cube array: multiple cubes (faces\u00D7layers), each face may carry multiple mips */\nexport function getTextureCubeArraySubresources(data: TextureCubeArrayData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n data.forEach((cubeData, cubeIndex) => {\n for (const [face, faceData] of Object.entries(cubeData)) {\n const faceDepth = getCubeArrayFaceIndex(cubeIndex, face as TextureCubeFace);\n subresources.push(...getTexture2DSubresources(faceDepth, faceData));\n }\n });\n return subresources;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, type CommandEncoder, Texture} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport {DynamicTexture} from '../dynamic-texture/dynamic-texture';\nimport {ClipSpace, ClipSpaceProps} from './clip-space';\n\nconst backgroundModule = {\n name: 'background',\n uniformTypes: {\n scale: 'vec2<f32>',\n flipY: 'i32'\n }\n} as const satisfies ShaderModule<{}, {scale: [number, number]; flipY: number}>;\n\nconst BACKGROUND_FS_WGSL = /* wgsl */ `\\\n@group(0) @binding(auto) var backgroundTexture: texture_2d<f32>;\n@group(0) @binding(auto) var backgroundTextureSampler: sampler;\nstruct backgroundUniforms {\n scale: vec2<f32>,\n flipY: i32,\n};\n@group(0) @binding(auto) var<uniform> background: backgroundUniforms;\n\nfn billboardTexture_getTextureUV(uv: vec2<f32>) -> vec2<f32> {\n let scale: vec2<f32> = background.scale;\n var position: vec2<f32> = (uv - vec2<f32>(0.5, 0.5)) / scale + vec2<f32>(0.5, 0.5);\n if (background.flipY != 0) {\n position.y = 1.0 - position.y;\n }\n return position;\n}\n\n@fragment\nfn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4<f32> {\n let position: vec2<f32> = billboardTexture_getTextureUV(inputs.uv);\n return textureSample(backgroundTexture, backgroundTextureSampler, position);\n}\n`;\n\nconst BACKGROUND_FS = /* glsl */ `\\\n#version 300 es\nprecision highp float;\n\nuniform sampler2D backgroundTexture;\n\nlayout(std140) uniform backgroundUniforms {\n vec2 scale;\n int flipY;\n} background;\n\nin vec2 coordinate;\nout vec4 fragColor;\n\nvec2 billboardTexture_getTextureUV(vec2 coord) {\n vec2 position = (coord - 0.5) / background.scale + 0.5;\n if (background.flipY != 0) {\n position.y = 1.0 - position.y;\n }\n return position;\n}\n\nvoid main(void) {\n vec2 position = billboardTexture_getTextureUV(coordinate);\n fragColor = texture(backgroundTexture, position);\n}\n`;\n\n/**\n * Props for a Model that renders a bitmap into the \"background\", i.e covering the screen\n */\nexport type BackgroundTextureModelProps = ClipSpaceProps & {\n /** id of this model */\n id?: string;\n /** The texture to render */\n backgroundTexture: Texture | DynamicTexture;\n /** If true, the texture is rendered into transparent areas of the screen only, i.e blended in where background alpha is small */\n blend?: boolean;\n /** If true, flip the sampled texture vertically before drawing. */\n flipY?: boolean;\n};\n\n/**\n * Model that renders a bitmap into the \"background\", i.e covering the screen\n */\nexport class BackgroundTextureModel extends ClipSpace {\n backgroundTexture: Texture = null!;\n flipY = false;\n\n constructor(device: Device, props: BackgroundTextureModelProps) {\n super(device, {\n ...props,\n id: props.id || 'background-texture-model',\n source: BACKGROUND_FS_WGSL,\n fs: BACKGROUND_FS,\n modules: [...(props.modules || []), backgroundModule],\n parameters: {\n depthWriteEnabled: false,\n ...(props.parameters || {}),\n ...(props.blend\n ? {\n blend: true,\n blendColorOperation: 'add',\n blendAlphaOperation: 'add',\n blendColorSrcFactor: 'one-minus-dst-alpha',\n blendColorDstFactor: 'one',\n blendAlphaSrcFactor: 'one-minus-dst-alpha',\n blendAlphaDstFactor: 'one'\n }\n : {})\n }\n });\n\n if (!props.backgroundTexture) {\n throw new Error('BackgroundTextureModel requires a backgroundTexture prop');\n }\n this.setProps(props);\n }\n\n /** Update the background texture */\n setProps(props: Partial<BackgroundTextureModelProps>): void {\n const {backgroundTexture} = props;\n if (props.flipY !== undefined) {\n this.flipY = props.flipY;\n if (this.backgroundTexture) {\n this.updateScale(this.backgroundTexture);\n }\n }\n\n if (backgroundTexture) {\n this.setBindings({backgroundTexture});\n\n if (backgroundTexture.isReady) {\n const texture =\n backgroundTexture instanceof DynamicTexture\n ? backgroundTexture.texture\n : backgroundTexture;\n this.backgroundTexture = texture;\n this.updateScale(texture);\n } else {\n backgroundTexture.ready.then(texture => {\n this.backgroundTexture = texture;\n this.updateScale(texture);\n });\n }\n }\n }\n\n override predraw(commandEncoder: CommandEncoder): void {\n // this.updateScale(this.backgroundTexture);\n super.predraw(commandEncoder);\n }\n\n updateScale(texture: Texture): void {\n if (!texture) {\n // Initial scale to avoid rendering issues before texture is loaded\n this.shaderInputs.setProps({background: {scale: [1, 1], flipY: 0}});\n return;\n }\n const [screenWidth, screenHeight] = this.device.getCanvasContext().getDrawingBufferSize();\n\n const textureWidth = texture.width;\n const textureHeight = texture.height;\n\n const screenAspect = screenWidth / screenHeight;\n const textureAspect = textureWidth / textureHeight;\n\n let scaleX = 1;\n let scaleY = 1;\n if (screenAspect > textureAspect) {\n scaleY = screenAspect / textureAspect;\n } else {\n scaleX = textureAspect / screenAspect;\n }\n\n this.shaderInputs.setProps({\n background: {scale: [scaleX, scaleY], flipY: this.flipY ? 1 : 0}\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\nexport type SphereGeometryProps = {\n id?: string;\n radius?: number;\n nlat?: number;\n nlong?: number;\n attributes?: any;\n};\n\n// Primitives inspired by TDL http://code.google.com/p/webglsamples/,\n// copyright 2011 Google Inc. new BSD License\n// (http://www.opensource.org/licenses/bsd-license.php).\nexport class SphereGeometry extends Geometry {\n constructor(props: SphereGeometryProps = {}) {\n const {id = uid('sphere-geometry')} = props;\n const {indices, attributes} = tesselateSphere(props);\n super({\n ...props,\n id,\n topology: 'triangle-list',\n indices,\n attributes: {...attributes, ...props.attributes}\n });\n }\n}\n\n/* eslint-disable max-statements, complexity */\nfunction tesselateSphere(props: SphereGeometryProps) {\n const {nlat = 10, nlong = 10} = props;\n\n const startLat = 0;\n const endLat = Math.PI;\n const latRange = endLat - startLat;\n const startLong = 0;\n const endLong = 2 * Math.PI;\n const longRange = endLong - startLong;\n const numVertices = (nlat + 1) * (nlong + 1);\n\n const radius = (n1: number, n2: number, n3: number, u: number, v: number) => props.radius || 1;\n\n const positions = new Float32Array(numVertices * 3);\n const normals = new Float32Array(numVertices * 3);\n const texCoords = new Float32Array(numVertices * 2);\n\n const IndexType = numVertices > 0xffff ? Uint32Array : Uint16Array;\n const indices = new IndexType(nlat * nlong * 6);\n\n // Create positions, normals and texCoords\n for (let y = 0; y <= nlat; y++) {\n for (let x = 0; x <= nlong; x++) {\n const u = x / nlong;\n const v = y / nlat;\n\n const index = x + y * (nlong + 1);\n const i2 = index * 2;\n const i3 = index * 3;\n\n const theta = longRange * u;\n const phi = latRange * v;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n const sinPhi = Math.sin(phi);\n const cosPhi = Math.cos(phi);\n const ux = cosTheta * sinPhi;\n const uy = cosPhi;\n const uz = sinTheta * sinPhi;\n\n const r = radius(ux, uy, uz, u, v);\n\n positions[i3 + 0] = r * ux;\n positions[i3 + 1] = r * uy;\n positions[i3 + 2] = r * uz;\n\n normals[i3 + 0] = ux;\n normals[i3 + 1] = uy;\n normals[i3 + 2] = uz;\n\n texCoords[i2 + 0] = u;\n texCoords[i2 + 1] = 1 - v;\n }\n }\n\n // Create indices\n const numVertsAround = nlong + 1;\n for (let x = 0; x < nlong; x++) {\n for (let y = 0; y < nlat; y++) {\n const index = (x * nlat + y) * 6;\n\n indices[index + 0] = y * numVertsAround + x;\n indices[index + 1] = y * numVertsAround + x + 1;\n indices[index + 2] = (y + 1) * numVertsAround + x;\n\n indices[index + 3] = (y + 1) * numVertsAround + x;\n indices[index + 4] = y * numVertsAround + x + 1;\n indices[index + 5] = (y + 1) * numVertsAround + x + 1;\n }\n }\n\n return {\n indices: {size: 1, value: indices},\n attributes: {\n POSITION: {size: 3, value: positions},\n NORMAL: {size: 3, value: normals},\n TEXCOORD_0: {size: 2, value: texCoords}\n }\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Buffer, Device, type RenderPass, type RenderPipelineParameters} from '@luma.gl/core';\nimport {Matrix4, type NumericArray} from '@math.gl/core';\nimport type {\n DirectionalLight,\n Light,\n PointLight,\n ShaderModule,\n SpotLight\n} from '@luma.gl/shadertools';\nimport {Model, type ModelProps} from '../model/model';\nimport {ShaderInputs} from '../shader-inputs';\nimport type {Geometry} from '../geometry/geometry';\n\nconst DEFAULT_POINT_LIGHT_RADIUS_FACTOR = 0.02;\nconst DEFAULT_SPOT_LIGHT_LENGTH_FACTOR = 0.12;\nconst DEFAULT_DIRECTIONAL_LIGHT_LENGTH_FACTOR = 0.15;\nconst DEFAULT_DIRECTIONAL_LIGHT_RADIUS_FACTOR = 0.2;\nconst DEFAULT_DIRECTION_FALLBACK: [number, number, number] = [0, 1, 0];\nconst DEFAULT_LIGHT_COLOR: [number, number, number] = [255, 255, 255];\nconst DEFAULT_MARKER_SCALE = 1;\nconst DIRECTIONAL_ANCHOR_DISTANCE_FACTOR = 0.35;\nconst LIGHT_COLOR_FACTOR = 255;\nconst MIN_SCENE_SCALE = 1;\nconst SPOTLIGHT_OUTER_CONE_EPSILON = 0.01;\n\nexport type LightModelBounds = [[number, number, number], [number, number, number]];\n\nexport type BaseLightModelProps = Omit<\n ModelProps,\n 'geometry' | 'modules' | 'shaderInputs' | 'source' | 'vs' | 'fs' | 'instanceCount'\n> & {\n lights: ReadonlyArray<Light>;\n viewMatrix: NumericArray;\n projectionMatrix: NumericArray;\n bounds?: LightModelBounds;\n markerScale?: number;\n};\n\nexport type PointLightModelProps = BaseLightModelProps & {\n pointLightRadius?: number;\n};\n\nexport type SpotLightModelProps = BaseLightModelProps & {\n spotLightLength?: number;\n};\n\nexport type DirectionalLightModelProps = BaseLightModelProps & {\n directionalLightLength?: number;\n};\n\ntype LightMarkerUniforms = {\n viewProjectionMatrix: Matrix4;\n};\n\nexport type LightMarkerInstanceData = {\n instanceCount: number;\n instancePositions: Float32Array;\n instanceDirections: Float32Array;\n instanceScales: Float32Array;\n instanceColors: Float32Array;\n};\n\ntype ManagedInstanceBuffers = Record<\n 'instancePosition' | 'instanceDirection' | 'instanceScale' | 'instanceColor',\n Buffer\n>;\n\ntype LightMarkerAnchorMode = 'centered' | 'apex';\n\ntype LightMarkerModelOptions<PropsT extends BaseLightModelProps> = {\n anchorMode: LightMarkerAnchorMode;\n buildInstanceData: (props: PropsT) => LightMarkerInstanceData;\n geometry: Geometry;\n idPrefix: string;\n sizePropNames: Array<keyof PropsT>;\n};\n\nconst LIGHT_MARKER_PARAMETERS: RenderPipelineParameters = {\n depthCompare: 'less-equal',\n depthWriteEnabled: false,\n cullMode: 'none'\n};\n\nconst INSTANCE_BUFFER_LAYOUT = [\n {name: 'instancePosition', format: 'float32x3', stepMode: 'instance'},\n {name: 'instanceDirection', format: 'float32x3', stepMode: 'instance'},\n {name: 'instanceScale', format: 'float32x3', stepMode: 'instance'},\n {name: 'instanceColor', format: 'float32x4', stepMode: 'instance'}\n] as const;\n\nconst lightMarker = {\n name: 'lightMarker',\n props: {} as LightMarkerUniforms,\n uniforms: {} as LightMarkerUniforms,\n uniformTypes: {\n viewProjectionMatrix: 'mat4x4<f32>'\n }\n} as const satisfies ShaderModule<LightMarkerUniforms, LightMarkerUniforms>;\n\nconst CENTERED_LOCAL_POSITION_WGSL = 'inputs.positions * inputs.instanceScale';\nconst APEX_LOCAL_POSITION_WGSL =\n 'vec3<f32>(inputs.positions.x * inputs.instanceScale.x, (inputs.positions.y - 0.5) * inputs.instanceScale.y, inputs.positions.z * inputs.instanceScale.z)';\nconst CENTERED_LOCAL_POSITION_GLSL = 'positions * instanceScale';\nconst APEX_LOCAL_POSITION_GLSL =\n 'vec3(positions.x * instanceScale.x, (positions.y - 0.5) * instanceScale.y, positions.z * instanceScale.z)';\n\nexport abstract class BaseLightModel<PropsT extends BaseLightModelProps> extends Model {\n protected lightModelProps: PropsT;\n protected _instanceData: LightMarkerInstanceData;\n protected _managedBuffers: ManagedInstanceBuffers;\n\n private readonly buildInstanceData: (props: PropsT) => LightMarkerInstanceData;\n private readonly sizePropNames: Array<keyof PropsT>;\n\n constructor(device: Device, props: PropsT, options: LightMarkerModelOptions<PropsT>) {\n const instanceData = options.buildInstanceData(props);\n const managedBuffers = createManagedInstanceBuffers(\n device,\n props.id || options.idPrefix,\n instanceData\n );\n const shaderInputs = new ShaderInputs<{\n lightMarker: typeof lightMarker.props;\n }>({lightMarker});\n shaderInputs.setProps({\n lightMarker: {viewProjectionMatrix: createViewProjectionMatrix(props)}\n });\n\n const {source, vs, fs} = getLightMarkerShaders(options.anchorMode);\n const modelProps: ModelProps = props;\n\n super(device, {\n ...modelProps,\n id: props.id || options.idPrefix,\n source,\n vs,\n fs,\n geometry: options.geometry,\n shaderInputs,\n bufferLayout: [...INSTANCE_BUFFER_LAYOUT],\n attributes: managedBuffers,\n instanceCount: instanceData.instanceCount,\n parameters: mergeLightMarkerParameters(props.parameters)\n });\n\n this.lightModelProps = props;\n this._instanceData = instanceData;\n this._managedBuffers = managedBuffers;\n this.buildInstanceData = options.buildInstanceData;\n this.sizePropNames = options.sizePropNames;\n }\n\n override destroy(): void {\n super.destroy();\n destroyManagedInstanceBuffers(this._managedBuffers);\n this._managedBuffers = {} as ManagedInstanceBuffers;\n }\n\n override draw(renderPass: RenderPass): boolean {\n if (this.instanceCount === 0) {\n return true;\n }\n return super.draw(renderPass);\n }\n\n setProps(props: Partial<PropsT>): void {\n this.lightModelProps = {...this.lightModelProps, ...props};\n\n if (props.parameters) {\n this.setParameters(mergeLightMarkerParameters(this.lightModelProps.parameters));\n }\n\n if ('viewMatrix' in props || 'projectionMatrix' in props) {\n this.shaderInputs.setProps({\n lightMarker: {viewProjectionMatrix: createViewProjectionMatrix(this.lightModelProps)}\n });\n this.setNeedsRedraw('lightMarker camera');\n }\n\n if (shouldRebuildInstanceData(props, this.sizePropNames)) {\n this.rebuildInstanceData();\n }\n }\n\n private rebuildInstanceData(): void {\n const nextInstanceData = this.buildInstanceData(this.lightModelProps);\n const nextManagedBuffers = createManagedInstanceBuffers(this.device, this.id, nextInstanceData);\n\n this.setAttributes(nextManagedBuffers);\n this.setInstanceCount(nextInstanceData.instanceCount);\n\n destroyManagedInstanceBuffers(this._managedBuffers);\n this._managedBuffers = nextManagedBuffers;\n this._instanceData = nextInstanceData;\n }\n}\n\nexport function buildPointLightInstanceData(props: PointLightModelProps): LightMarkerInstanceData {\n const pointLights = getPointLights(props.lights);\n const context = getLightMarkerContext(props);\n const pointLightRadius =\n props.pointLightRadius ??\n DEFAULT_POINT_LIGHT_RADIUS_FACTOR * context.sceneScale * context.markerScale;\n\n return createLightMarkerInstanceData(\n pointLights.length,\n (light, _index) => ({\n color: getDisplayColor(light),\n direction: DEFAULT_DIRECTION_FALLBACK,\n position: light.position,\n scale: [pointLightRadius, pointLightRadius, pointLightRadius]\n }),\n pointLights\n );\n}\n\nexport function buildSpotLightInstanceData(props: SpotLightModelProps): LightMarkerInstanceData {\n const spotLights = getSpotLights(props.lights);\n const context = getLightMarkerContext(props);\n const spotLightLength =\n props.spotLightLength ??\n DEFAULT_SPOT_LIGHT_LENGTH_FACTOR * context.sceneScale * context.markerScale;\n\n return createLightMarkerInstanceData(\n spotLights.length,\n (light, _index) => {\n const outerConeAngle = clamp(\n light.outerConeAngle ?? Math.PI / 4,\n 0,\n Math.PI / 2 - SPOTLIGHT_OUTER_CONE_EPSILON\n );\n const radius = Math.tan(outerConeAngle) * spotLightLength;\n\n return {\n color: getDisplayColor(light),\n direction: normalizeDirection(light.direction),\n position: light.position,\n scale: [radius, spotLightLength, radius]\n };\n },\n spotLights\n );\n}\n\nexport function buildDirectionalLightInstanceData(\n props: DirectionalLightModelProps\n): LightMarkerInstanceData {\n const directionalLights = getDirectionalLights(props.lights);\n const context = getLightMarkerContext(props);\n const directionalLightLength =\n props.directionalLightLength ??\n DEFAULT_DIRECTIONAL_LIGHT_LENGTH_FACTOR * context.sceneScale * context.markerScale;\n const directionalLightRadius = directionalLightLength * DEFAULT_DIRECTIONAL_LIGHT_RADIUS_FACTOR;\n\n return createLightMarkerInstanceData(\n directionalLights.length,\n (light, _index) => {\n const direction = normalizeDirection(light.direction);\n const position = [\n context.sceneCenter[0] -\n direction[0] * context.sceneScale * DIRECTIONAL_ANCHOR_DISTANCE_FACTOR,\n context.sceneCenter[1] -\n direction[1] * context.sceneScale * DIRECTIONAL_ANCHOR_DISTANCE_FACTOR,\n context.sceneCenter[2] -\n direction[2] * context.sceneScale * DIRECTIONAL_ANCHOR_DISTANCE_FACTOR\n ] as [number, number, number];\n\n return {\n color: getDisplayColor(light),\n direction,\n position,\n scale: [directionalLightRadius, directionalLightLength, directionalLightRadius]\n };\n },\n directionalLights\n );\n}\n\nexport function getPointLights(lights: ReadonlyArray<Light>): PointLight[] {\n return lights.filter((light): light is PointLight => light.type === 'point');\n}\n\nexport function getSpotLights(lights: ReadonlyArray<Light>): SpotLight[] {\n return lights.filter((light): light is SpotLight => light.type === 'spot');\n}\n\nexport function getDirectionalLights(lights: ReadonlyArray<Light>): DirectionalLight[] {\n return lights.filter((light): light is DirectionalLight => light.type === 'directional');\n}\n\nexport function getLightMarkerContext(props: BaseLightModelProps): {\n bounds: LightModelBounds;\n markerScale: number;\n sceneCenter: [number, number, number];\n sceneScale: number;\n} {\n const bounds = getSceneBounds(props.lights, props.bounds);\n const sceneCenter = [\n (bounds[0][0] + bounds[1][0]) / 2,\n (bounds[0][1] + bounds[1][1]) / 2,\n (bounds[0][2] + bounds[1][2]) / 2\n ] as [number, number, number];\n const sceneScale = Math.max(\n Math.hypot(\n bounds[1][0] - bounds[0][0],\n bounds[1][1] - bounds[0][1],\n bounds[1][2] - bounds[0][2]\n ),\n MIN_SCENE_SCALE\n );\n\n return {\n bounds,\n markerScale: Math.max(props.markerScale ?? DEFAULT_MARKER_SCALE, 0),\n sceneCenter,\n sceneScale\n };\n}\n\nexport function getDisplayColor(light: {\n color?: Readonly<[number, number, number]>;\n intensity?: number;\n}): [number, number, number, number] {\n const color = light.color || DEFAULT_LIGHT_COLOR;\n const intensity = Math.max(light.intensity ?? 1, 0);\n const brightness = clamp(0.35 + 0.3 * Math.log10(intensity + 1), 0.35, 1);\n\n return [\n clamp(color[0] / LIGHT_COLOR_FACTOR, 0, 1) * brightness,\n clamp(color[1] / LIGHT_COLOR_FACTOR, 0, 1) * brightness,\n clamp(color[2] / LIGHT_COLOR_FACTOR, 0, 1) * brightness,\n 1\n ];\n}\n\nexport function normalizeDirection(\n direction?: Readonly<[number, number, number]>\n): [number, number, number] {\n const [x, y, z] = direction || DEFAULT_DIRECTION_FALLBACK;\n const length = Math.hypot(x, y, z);\n if (length === 0) {\n return [...DEFAULT_DIRECTION_FALLBACK];\n }\n return [x / length, y / length, z / length];\n}\n\nfunction createLightMarkerInstanceData<TLight>(\n instanceCount: number,\n getInstance: (\n light: TLight,\n index: number\n ) => {\n color: [number, number, number, number];\n direction: [number, number, number];\n position: Readonly<NumericArray>;\n scale: [number, number, number];\n },\n lights: TLight[] = []\n): LightMarkerInstanceData {\n const instancePositions = new Float32Array(instanceCount * 3);\n const instanceDirections = new Float32Array(instanceCount * 3);\n const instanceScales = new Float32Array(instanceCount * 3);\n const instanceColors = new Float32Array(instanceCount * 4);\n\n for (const [index, light] of lights.entries()) {\n const instance = getInstance(light, index);\n instancePositions.set(instance.position, index * 3);\n instanceDirections.set(instance.direction, index * 3);\n instanceScales.set(instance.scale, index * 3);\n instanceColors.set(instance.color, index * 4);\n }\n\n return {\n instanceCount,\n instancePositions,\n instanceDirections,\n instanceScales,\n instanceColors\n };\n}\n\nfunction getSceneBounds(lights: ReadonlyArray<Light>, bounds?: LightModelBounds): LightModelBounds {\n if (bounds) {\n return cloneBounds(bounds);\n }\n\n const positions = [\n ...getPointLights(lights).map(light => light.position),\n ...getSpotLights(lights).map(light => light.position)\n ];\n\n if (positions.length === 0) {\n return [\n [-0.5, -0.5, -0.5],\n [0.5, 0.5, 0.5]\n ];\n }\n\n const minBounds: [number, number, number] = [...positions[0]] as [number, number, number];\n const maxBounds: [number, number, number] = [...positions[0]] as [number, number, number];\n\n for (const position of positions.slice(1)) {\n minBounds[0] = Math.min(minBounds[0], position[0]);\n minBounds[1] = Math.min(minBounds[1], position[1]);\n minBounds[2] = Math.min(minBounds[2], position[2]);\n\n maxBounds[0] = Math.max(maxBounds[0], position[0]);\n maxBounds[1] = Math.max(maxBounds[1], position[1]);\n maxBounds[2] = Math.max(maxBounds[2], position[2]);\n }\n\n return [minBounds, maxBounds];\n}\n\nfunction cloneBounds(bounds: LightModelBounds): LightModelBounds {\n return [[...bounds[0]] as [number, number, number], [...bounds[1]] as [number, number, number]];\n}\n\nfunction createManagedInstanceBuffers(\n device: Device,\n idPrefix: string,\n instanceData: LightMarkerInstanceData\n): ManagedInstanceBuffers {\n return {\n instancePosition: device.createBuffer({\n id: `${idPrefix}-instance-position`,\n data: getBufferDataOrPlaceholder(instanceData.instancePositions, 3)\n }),\n instanceDirection: device.createBuffer({\n id: `${idPrefix}-instance-direction`,\n data: getBufferDataOrPlaceholder(instanceData.instanceDirections, 3)\n }),\n instanceScale: device.createBuffer({\n id: `${idPrefix}-instance-scale`,\n data: getBufferDataOrPlaceholder(instanceData.instanceScales, 3)\n }),\n instanceColor: device.createBuffer({\n id: `${idPrefix}-instance-color`,\n data: getBufferDataOrPlaceholder(instanceData.instanceColors, 4)\n })\n };\n}\n\nfunction getBufferDataOrPlaceholder(data: Float32Array, size: number): Float32Array {\n return data.length > 0 ? data : new Float32Array(size);\n}\n\nfunction destroyManagedInstanceBuffers(managedBuffers: Partial<ManagedInstanceBuffers>): void {\n for (const buffer of Object.values(managedBuffers)) {\n buffer?.destroy();\n }\n}\n\nfunction createViewProjectionMatrix(\n props: Pick<BaseLightModelProps, 'projectionMatrix' | 'viewMatrix'>\n): Matrix4 {\n return new Matrix4(props.projectionMatrix).multiplyRight(props.viewMatrix);\n}\n\nfunction shouldRebuildInstanceData<PropsT extends BaseLightModelProps>(\n props: Partial<PropsT>,\n sizePropNames: Array<keyof PropsT>\n): boolean {\n if ('lights' in props || 'bounds' in props || 'markerScale' in props) {\n return true;\n }\n return sizePropNames.some(sizePropName => sizePropName in props);\n}\n\nfunction mergeLightMarkerParameters(\n parameters?: RenderPipelineParameters\n): RenderPipelineParameters {\n return {\n ...LIGHT_MARKER_PARAMETERS,\n ...(parameters || {})\n };\n}\n\nfunction getLightMarkerShaders(anchorMode: LightMarkerAnchorMode): {\n fs: string;\n source: string;\n vs: string;\n} {\n const localPositionWGSL =\n anchorMode === 'apex' ? APEX_LOCAL_POSITION_WGSL : CENTERED_LOCAL_POSITION_WGSL;\n const localPositionGLSL =\n anchorMode === 'apex' ? APEX_LOCAL_POSITION_GLSL : CENTERED_LOCAL_POSITION_GLSL;\n\n return {\n source: `\\\nstruct lightMarkerUniforms {\n viewProjectionMatrix: mat4x4<f32>,\n};\n\n@group(0) @binding(auto) var<uniform> lightMarker : lightMarkerUniforms;\n\nstruct VertexInputs {\n @location(0) positions : vec3<f32>,\n @location(1) instancePosition : vec3<f32>,\n @location(2) instanceDirection : vec3<f32>,\n @location(3) instanceScale : vec3<f32>,\n @location(4) instanceColor : vec4<f32>,\n};\n\nstruct FragmentInputs {\n @builtin(position) Position : vec4<f32>,\n @location(0) color : vec4<f32>,\n};\n\nfn lightMarker_rotate(localPosition: vec3<f32>, direction: vec3<f32>) -> vec3<f32> {\n let forward = normalize(direction);\n var helperAxis = vec3<f32>(0.0, 1.0, 0.0);\n if (abs(forward.y) > 0.999) {\n helperAxis = vec3<f32>(1.0, 0.0, 0.0);\n }\n\n let tangent = normalize(cross(helperAxis, forward));\n let bitangent = cross(forward, tangent);\n return tangent * localPosition.x + forward * localPosition.y + bitangent * localPosition.z;\n}\n\n@vertex\nfn vertexMain(inputs: VertexInputs) -> FragmentInputs {\n var outputs : FragmentInputs;\n let localPosition = ${localPositionWGSL};\n let worldPosition = inputs.instancePosition + lightMarker_rotate(localPosition, inputs.instanceDirection);\n outputs.Position = lightMarker.viewProjectionMatrix * vec4<f32>(worldPosition, 1.0);\n outputs.color = inputs.instanceColor;\n return outputs;\n}\n\n@fragment\nfn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4<f32> {\n return inputs.color;\n}\n`,\n vs: `\\\n#version 300 es\n\nin vec3 positions;\nin vec3 instancePosition;\nin vec3 instanceDirection;\nin vec3 instanceScale;\nin vec4 instanceColor;\n\nlayout(std140) uniform lightMarkerUniforms {\n mat4 viewProjectionMatrix;\n} lightMarker;\n\nout vec4 vColor;\n\nvec3 lightMarker_rotate(vec3 localPosition, vec3 direction) {\n vec3 forward = normalize(direction);\n vec3 helperAxis = abs(forward.y) > 0.999 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);\n vec3 tangent = normalize(cross(helperAxis, forward));\n vec3 bitangent = cross(forward, tangent);\n return tangent * localPosition.x + forward * localPosition.y + bitangent * localPosition.z;\n}\n\nvoid main(void) {\n vec3 localPosition = ${localPositionGLSL};\n vec3 worldPosition = instancePosition + lightMarker_rotate(localPosition, instanceDirection);\n gl_Position = lightMarker.viewProjectionMatrix * vec4(worldPosition, 1.0);\n vColor = instanceColor;\n}\n`,\n fs: `\\\n#version 300 es\nprecision highp float;\n\nin vec4 vColor;\nout vec4 fragColor;\n\nvoid main(void) {\n fragColor = vColor;\n}\n`\n };\n}\n\nfunction clamp(value: number, minValue: number, maxValue: number): number {\n return Math.min(maxValue, Math.max(minValue, value));\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '@luma.gl/core';\nimport {SphereGeometry} from '../geometries/sphere-geometry';\nimport {\n BaseLightModel,\n buildPointLightInstanceData,\n type PointLightModelProps\n} from './light-model-utils';\n\nconst POINT_LIGHT_GEOMETRY = new SphereGeometry({\n nlat: 8,\n nlong: 12,\n radius: 1\n});\n\nexport type {PointLightModelProps} from './light-model-utils';\n\nexport class PointLightModel extends BaseLightModel<PointLightModelProps> {\n constructor(device: Device, props: PointLightModelProps) {\n super(device, props, {\n anchorMode: 'centered',\n buildInstanceData: buildPointLightInstanceData,\n geometry: POINT_LIGHT_GEOMETRY,\n idPrefix: 'point-light-model',\n sizePropNames: ['pointLightRadius']\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\nconst INDEX_OFFSETS = {\n x: [2, 0, 1],\n y: [0, 1, 2],\n z: [1, 2, 0]\n};\n\nexport type TruncatedConeGeometryProps = {\n topRadius?: number;\n bottomRadius?: number;\n topCap?: boolean;\n bottomCap?: boolean;\n height?: number;\n nradial?: number;\n nvertical?: number;\n verticalAxis?: 'x' | 'y' | 'z';\n};\n\n/**\n * Primitives inspired by TDL http://code.google.com/p/webglsamples/,\n * copyright 2011 Google Inc. new BSD License\n * (http://www.opensource.org/licenses/bsd-license.php).\n */\nexport class TruncatedConeGeometry extends Geometry {\n constructor(props: TruncatedConeGeometryProps & {id?: string; attributes?: any} = {}) {\n const {id = uid('truncated-code-geometry')} = props;\n const {indices, attributes} = tesselateTruncatedCone(props);\n super({\n ...props,\n id,\n topology: 'triangle-list',\n indices,\n attributes: {\n POSITION: {size: 3, value: attributes.POSITION},\n NORMAL: {size: 3, value: attributes.NORMAL},\n TEXCOORD_0: {size: 2, value: attributes.TEXCOORD_0},\n ...props.attributes\n }\n });\n }\n}\n\n/* eslint-disable max-statements, complexity */\nfunction tesselateTruncatedCone(props: TruncatedConeGeometryProps = {}) {\n const {\n bottomRadius = 0,\n topRadius = 0,\n height = 1,\n nradial = 10,\n nvertical = 10,\n verticalAxis = 'y',\n topCap = false,\n bottomCap = false\n } = props;\n\n const extra = (topCap ? 2 : 0) + (bottomCap ? 2 : 0);\n const numVertices = (nradial + 1) * (nvertical + 1 + extra);\n\n const slant = Math.atan2(bottomRadius - topRadius, height);\n const msin = Math.sin;\n const mcos = Math.cos;\n const mpi = Math.PI;\n const cosSlant = mcos(slant);\n const sinSlant = msin(slant);\n const start = topCap ? -2 : 0;\n const end = nvertical + (bottomCap ? 2 : 0);\n const vertsAroundEdge = nradial + 1;\n\n const indices = new Uint16Array(nradial * (nvertical + extra) * 6);\n const indexOffset = INDEX_OFFSETS[verticalAxis];\n\n const positions = new Float32Array(numVertices * 3);\n const normals = new Float32Array(numVertices * 3);\n const texCoords = new Float32Array(numVertices * 2);\n\n let i3 = 0;\n let i2 = 0;\n for (let i = start; i <= end; i++) {\n let v = i / nvertical;\n let y = height * v;\n let ringRadius;\n\n if (i < 0) {\n y = 0;\n v = 1;\n ringRadius = bottomRadius;\n } else if (i > nvertical) {\n y = height;\n v = 1;\n ringRadius = topRadius;\n } else {\n ringRadius = bottomRadius + (topRadius - bottomRadius) * (i / nvertical);\n }\n if (i === -2 || i === nvertical + 2) {\n ringRadius = 0;\n v = 0;\n }\n y -= height / 2;\n for (let j = 0; j < vertsAroundEdge; j++) {\n const sin = msin((j * mpi * 2) / nradial);\n const cos = mcos((j * mpi * 2) / nradial);\n\n positions[i3 + indexOffset[0]] = sin * ringRadius;\n positions[i3 + indexOffset[1]] = y;\n positions[i3 + indexOffset[2]] = cos * ringRadius;\n\n normals[i3 + indexOffset[0]] = i < 0 || i > nvertical ? 0 : sin * cosSlant;\n normals[i3 + indexOffset[1]] = i < 0 ? -1 : i > nvertical ? 1 : sinSlant;\n normals[i3 + indexOffset[2]] = i < 0 || i > nvertical ? 0 : cos * cosSlant;\n\n texCoords[i2 + 0] = j / nradial;\n texCoords[i2 + 1] = v;\n\n i2 += 2;\n i3 += 3;\n }\n }\n\n for (let i = 0; i < nvertical + extra; i++) {\n for (let j = 0; j < nradial; j++) {\n const index = (i * nradial + j) * 6;\n indices[index + 0] = vertsAroundEdge * (i + 0) + 0 + j;\n indices[index + 1] = vertsAroundEdge * (i + 0) + 1 + j;\n indices[index + 2] = vertsAroundEdge * (i + 1) + 1 + j;\n indices[index + 3] = vertsAroundEdge * (i + 0) + 0 + j;\n indices[index + 4] = vertsAroundEdge * (i + 1) + 1 + j;\n indices[index + 5] = vertsAroundEdge * (i + 1) + 0 + j;\n }\n }\n\n return {\n indices,\n attributes: {\n POSITION: positions,\n NORMAL: normals,\n TEXCOORD_0: texCoords\n }\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TruncatedConeGeometryProps} from './truncated-cone-geometry';\nimport {TruncatedConeGeometry} from './truncated-cone-geometry';\nimport {uid} from '../utils/uid';\n\nexport type ConeGeometryProps = Omit<\n TruncatedConeGeometryProps,\n 'topRadius' | 'bottomRadius' | 'topCap' | 'bottomCap'\n> & {\n id?: string;\n radius?: number;\n cap?: boolean;\n attributes?: any;\n};\n\nexport class ConeGeometry extends TruncatedConeGeometry {\n constructor(props: ConeGeometryProps = {}) {\n const {id = uid('cone-geometry'), radius = 1, cap = true} = props;\n super({\n ...props,\n id,\n topRadius: 0,\n topCap: Boolean(cap),\n bottomCap: Boolean(cap),\n bottomRadius: radius\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '@luma.gl/core';\nimport {ConeGeometry} from '../geometries/cone-geometry';\nimport {\n BaseLightModel,\n buildSpotLightInstanceData,\n type SpotLightModelProps\n} from './light-model-utils';\n\nconst SPOT_LIGHT_GEOMETRY = new ConeGeometry({\n cap: true,\n nradial: 16,\n nvertical: 1,\n radius: 1\n});\n\nexport type {SpotLightModelProps} from './light-model-utils';\n\nexport class SpotLightModel extends BaseLightModel<SpotLightModelProps> {\n constructor(device: Device, props: SpotLightModelProps) {\n super(device, props, {\n anchorMode: 'apex',\n buildInstanceData: buildSpotLightInstanceData,\n geometry: SPOT_LIGHT_GEOMETRY,\n idPrefix: 'spot-light-model',\n sizePropNames: ['spotLightLength']\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '@luma.gl/core';\nimport {ConeGeometry} from '../geometries/cone-geometry';\nimport {\n BaseLightModel,\n buildDirectionalLightInstanceData,\n type DirectionalLightModelProps\n} from './light-model-utils';\n\nconst DIRECTIONAL_LIGHT_GEOMETRY = new ConeGeometry({\n cap: true,\n nradial: 12,\n nvertical: 1,\n radius: 1\n});\n\nexport type {DirectionalLightModelProps} from './light-model-utils';\n\nexport class DirectionalLightModel extends BaseLightModel<DirectionalLightModelProps> {\n constructor(device: Device, props: DirectionalLightModelProps) {\n super(device, props, {\n anchorMode: 'apex',\n buildInstanceData: buildDirectionalLightInstanceData,\n geometry: DIRECTIONAL_LIGHT_GEOMETRY,\n idPrefix: 'directional-light-model',\n sizePropNames: ['directionalLightLength']\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Vector3, Matrix4, NumericArray} from '@math.gl/core';\nimport {uid} from '../utils/uid';\n\nfunction assert(condition: boolean, message?: string): asserts condition {\n if (!condition) {\n throw new Error(message);\n }\n}\n\n/** Properties for creating a new Scenegraph */\nexport type ScenegraphNodeProps = {\n id?: string;\n /** whether to display the object at all */\n display?: boolean;\n matrix?: NumericArray;\n position?: NumericArray;\n rotation?: NumericArray;\n scale?: NumericArray;\n update?: boolean;\n};\n\nexport class ScenegraphNode {\n readonly id: string;\n matrix: Matrix4 = new Matrix4();\n\n display = true;\n position = new Vector3();\n rotation = new Vector3();\n scale = new Vector3(1, 1, 1);\n userData: Record<string, unknown> = {};\n\n props: ScenegraphNodeProps = {};\n\n constructor(props: ScenegraphNodeProps = {}) {\n const {id} = props;\n\n this.id = id || uid(this.constructor.name);\n\n this._setScenegraphNodeProps(props);\n }\n\n getBounds(): [number[], number[]] | null {\n return null;\n }\n\n destroy(): void {}\n\n /** @deprecated use .destroy() */\n delete(): void {\n this.destroy();\n }\n setProps(props: ScenegraphNodeProps): this {\n this._setScenegraphNodeProps(props);\n return this;\n }\n\n toString(): string {\n return `{type: ScenegraphNode, id: ${this.id})}`;\n }\n\n setPosition(position: any): this {\n assert(position.length === 3, 'setPosition requires vector argument');\n this.position = position;\n return this;\n }\n\n setRotation(rotation: any): this {\n assert(rotation.length === 3 || rotation.length === 4, 'setRotation requires vector argument');\n this.rotation = rotation;\n return this;\n }\n\n setScale(scale: any): this {\n assert(scale.length === 3, 'setScale requires vector argument');\n this.scale = scale;\n return this;\n }\n\n setMatrix(matrix: any, copyMatrix: boolean = true): void {\n if (copyMatrix) {\n this.matrix.copy(matrix);\n } else {\n this.matrix = matrix;\n }\n }\n\n setMatrixComponents(components: {\n position?: any;\n rotation?: any;\n scale?: any;\n update?: boolean;\n }): this {\n const {position, rotation, scale, update = true} = components;\n if (position) {\n this.setPosition(position);\n }\n if (rotation) {\n this.setRotation(rotation);\n }\n if (scale) {\n this.setScale(scale);\n }\n if (update) {\n this.updateMatrix();\n }\n return this;\n }\n\n updateMatrix(): this {\n this.matrix.identity();\n this.matrix.translate(this.position);\n if (this.rotation.length === 4) {\n const rotationMatrix = new Matrix4().fromQuaternion(this.rotation);\n this.matrix.multiplyRight(rotationMatrix);\n } else {\n this.matrix.rotateXYZ(this.rotation);\n }\n this.matrix.scale(this.scale);\n\n return this;\n }\n\n update({position, rotation, scale}: {position?: any; rotation?: any; scale?: any} = {}): this {\n if (position) {\n this.setPosition(position);\n }\n if (rotation) {\n this.setRotation(rotation);\n }\n if (scale) {\n this.setScale(scale);\n }\n\n this.updateMatrix();\n\n return this;\n }\n\n getCoordinateUniforms(\n viewMatrix: any,\n modelMatrix?: any\n ): {\n viewMatrix: any;\n modelMatrix: any;\n objectMatrix: any;\n worldMatrix: any;\n worldInverseMatrix: any;\n worldInverseTransposeMatrix: any;\n } {\n // TODO - solve multiple class problem\n // assert(viewMatrix instanceof Matrix4);\n // assert(viewMatrix);\n modelMatrix = modelMatrix || this.matrix;\n const worldMatrix = new Matrix4(viewMatrix).multiplyRight(modelMatrix);\n const worldInverse = worldMatrix.invert();\n const worldInverseTranspose = worldInverse.transpose();\n\n return {\n viewMatrix,\n modelMatrix,\n objectMatrix: modelMatrix,\n worldMatrix,\n worldInverseMatrix: worldInverse,\n worldInverseTransposeMatrix: worldInverseTranspose\n };\n }\n\n // TODO - copied code, not yet vetted\n /*\n transform() {\n if (!this.parent) {\n this.endPosition.set(this.position);\n this.endRotation.set(this.rotation);\n this.endScale.set(this.scale);\n } else {\n const parent = this.parent;\n this.endPosition.set(this.position.add(parent.endPosition));\n this.endRotation.set(this.rotation.add(parent.endRotation));\n this.endScale.set(this.scale.add(parent.endScale));\n }\n\n const ch = this.children;\n for (let i = 0; i < ch.length; ++i) {\n ch[i].transform();\n }\n\n return this;\n }\n */\n\n _setScenegraphNodeProps(props: ScenegraphNodeProps): void {\n // if ('display' in props) {\n // this.display = props.display;\n // }\n\n if (props?.position) {\n this.setPosition(props.position);\n }\n if (props?.rotation) {\n this.setRotation(props.rotation);\n }\n if (props?.scale) {\n this.setScale(props.scale);\n }\n\n this.updateMatrix();\n\n // Matrix overwrites other props\n if (props?.matrix) {\n this.setMatrix(props.matrix);\n }\n\n Object.assign(this.props, props);\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport type {NumericArray} from '@math.gl/core';\nimport {log} from '@luma.gl/core';\nimport {ScenegraphNode, ScenegraphNodeProps} from './scenegraph-node';\nimport {\n areScenegraphBoundsDefined,\n expandScenegraphBounds,\n makeEmptyScenegraphBounds\n} from './scenegraph-bounds';\nimport type {ScenegraphBounds} from './scenegraph-bounds';\n\nexport type GroupNodeProps = ScenegraphNodeProps & {\n children?: ScenegraphNode[];\n};\n\n/** Camera-relative ordering options for a flattened scenegraph traversal. */\nexport type DepthSortedTraversalOptions = {\n viewMatrix: NumericArray;\n worldMatrix?: NumericArray;\n order?: 'back-to-front' | 'front-to-back';\n};\n\n/** Model transform, local aggregate bounds, and positive camera depth for one visited node. */\nexport type DepthSortedTraversalContext = {\n worldMatrix: Matrix4;\n bounds: [number[], number[]] | null;\n depth: number;\n};\n\nexport class GroupNode extends ScenegraphNode {\n children: ScenegraphNode[];\n\n constructor(children: ScenegraphNode[]);\n constructor(props?: GroupNodeProps);\n\n constructor(props: ScenegraphNode[] | GroupNodeProps = {}) {\n props = Array.isArray(props) ? {children: props} : props;\n const {children = []} = props;\n log.assert(\n children.every(child => child instanceof ScenegraphNode),\n 'every child must an instance of ScenegraphNode'\n );\n super(props);\n this.children = children;\n }\n\n override getBounds(): ScenegraphBounds | null {\n const result = makeEmptyScenegraphBounds();\n\n this.traverse((node, {worldMatrix}) => {\n const bounds = node.getBounds();\n if (!bounds) {\n return;\n }\n const nodeWorldMatrix = new Matrix4(worldMatrix).multiplyRight(node.matrix);\n expandScenegraphBounds(result, bounds, nodeWorldMatrix);\n });\n return areScenegraphBoundsDefined(result) ? result : null;\n }\n\n override destroy(): void {\n this.children.forEach(child => child.destroy());\n this.removeAll();\n super.destroy();\n }\n\n // Unpacks arrays and nested arrays of children\n add(...children: (ScenegraphNode | ScenegraphNode[])[]): this {\n for (const child of children) {\n if (Array.isArray(child)) {\n this.add(...child);\n } else {\n this.children.push(child);\n }\n }\n return this;\n }\n\n remove(child: ScenegraphNode): this {\n const children = this.children;\n const indexOf = children.indexOf(child);\n if (indexOf > -1) {\n children.splice(indexOf, 1);\n }\n return this;\n }\n\n removeAll(): this {\n this.children = [];\n return this;\n }\n\n traverse(\n visitor: (node: ScenegraphNode, context: {worldMatrix: Matrix4}) => void,\n {worldMatrix = new Matrix4()} = {}\n ) {\n const modelMatrix = new Matrix4(worldMatrix).multiplyRight(this.matrix);\n\n for (const child of this.children) {\n if (child instanceof GroupNode) {\n child.traverse(visitor, {worldMatrix: modelMatrix});\n } else {\n visitor(child, {worldMatrix: modelMatrix});\n }\n }\n }\n\n /** Visits leaf nodes ordered by the camera-space centers of their aggregate bounds. */\n traverseDepthSorted(\n visitor: (node: ScenegraphNode, context: DepthSortedTraversalContext) => void,\n {viewMatrix, worldMatrix = new Matrix4(), order = 'back-to-front'}: DepthSortedTraversalOptions\n ): void {\n const cameraMatrix = new Matrix4(viewMatrix);\n const nodes: {node: ScenegraphNode; context: DepthSortedTraversalContext; index: number}[] = [];\n\n this.traverse(\n (node, context) => {\n const bounds = node.getBounds();\n const center = bounds\n ? new Vector3(bounds[0]).add(bounds[1]).divide([2, 2, 2])\n : new Vector3();\n const nodeWorldMatrix = new Matrix4(context.worldMatrix).multiplyRight(node.matrix);\n nodeWorldMatrix.transformAsPoint(center, center);\n cameraMatrix.transformAsPoint(center, center);\n nodes.push({\n node,\n context: {worldMatrix: nodeWorldMatrix, bounds, depth: -center[2]},\n index: nodes.length\n });\n },\n {worldMatrix: new Matrix4(worldMatrix)}\n );\n\n const direction = order === 'back-to-front' ? -1 : 1;\n nodes.sort(\n (first, second) =>\n direction * (first.context.depth - second.context.depth) || first.index - second.index\n );\n\n for (const {node, context} of nodes) {\n visitor(node, context);\n }\n }\n\n preorderTraversal(\n visitor: (node: ScenegraphNode, context: {worldMatrix: Matrix4}) => void,\n {worldMatrix = new Matrix4()} = {}\n ) {\n const modelMatrix = new Matrix4(worldMatrix).multiplyRight(this.matrix);\n visitor(this, {worldMatrix: modelMatrix});\n\n for (const child of this.children) {\n if (child instanceof GroupNode) {\n child.preorderTraversal(visitor, {worldMatrix: modelMatrix});\n } else {\n visitor(child, {worldMatrix: modelMatrix});\n }\n }\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport type {NumericArray} from '@math.gl/core';\n\n/** Axis-aligned bounds in a scenegraph node's local coordinate system. */\nexport type ScenegraphBounds = [[number, number, number], [number, number, number]];\n\nexport function makeEmptyScenegraphBounds(): ScenegraphBounds {\n return [\n [Infinity, Infinity, Infinity],\n [-Infinity, -Infinity, -Infinity]\n ];\n}\n\nexport function expandScenegraphBounds(\n targetBounds: ScenegraphBounds,\n sourceBounds: [number[], number[]],\n transform: NumericArray\n): void {\n const transformMatrix = new Matrix4(transform);\n\n for (let cornerIndex = 0; cornerIndex < 8; cornerIndex++) {\n const corner = new Vector3(\n sourceBounds[cornerIndex & 0b001 ? 1 : 0][0],\n sourceBounds[cornerIndex & 0b010 ? 1 : 0][1],\n sourceBounds[cornerIndex & 0b100 ? 1 : 0][2]\n );\n transformMatrix.transformAsPoint(corner, corner);\n\n for (let componentIndex = 0; componentIndex < 3; componentIndex++) {\n targetBounds[0][componentIndex] = Math.min(\n targetBounds[0][componentIndex],\n corner[componentIndex]\n );\n targetBounds[1][componentIndex] = Math.max(\n targetBounds[1][componentIndex],\n corner[componentIndex]\n );\n }\n }\n}\n\nexport function areScenegraphBoundsDefined(bounds: ScenegraphBounds): boolean {\n return Number.isFinite(bounds[0][0]);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {RenderPass} from '@luma.gl/core';\nimport type {NumericArray} from '@math.gl/core';\nimport {ScenegraphNode, ScenegraphNodeProps} from './scenegraph-node';\nimport {\n areScenegraphBoundsDefined,\n expandScenegraphBounds,\n makeEmptyScenegraphBounds\n} from './scenegraph-bounds';\nimport type {ScenegraphBounds} from './scenegraph-bounds';\nimport {Model} from '../model/model';\n\nexport type ModelNodeProps = ScenegraphNodeProps & {\n model: Model;\n managedResources?: any[];\n /** Bounds of one model instance before instance and node transforms. */\n bounds?: ScenegraphBounds;\n /** Optional per-instance transforms used to calculate aggregate local bounds. */\n instanceMatrices?: readonly NumericArray[];\n};\n\nexport class ModelNode extends ScenegraphNode {\n readonly model: Model;\n readonly instanceMatrices: readonly NumericArray[] | null;\n bounds: ScenegraphBounds | null = null;\n managedResources: any[];\n\n // TODO - is this used? override callbacks to make sure we call them with this\n // onBeforeRender = null;\n // onAfterRender = null;\n // AfterRender = null;\n\n constructor(props: ModelNodeProps) {\n super(props);\n\n // Create new Model or used supplied Model\n this.model = props.model;\n this.managedResources = props.managedResources || [];\n this.instanceMatrices = props.instanceMatrices || null;\n this.bounds = props.bounds\n ? this.instanceMatrices\n ? getInstancedScenegraphBounds(props.bounds, this.instanceMatrices)\n : props.bounds\n : null;\n this.setProps(props);\n }\n\n override destroy(): void {\n if (this.model) {\n this.model.destroy();\n // @ts-expect-error\n this.model = null;\n }\n this.managedResources.forEach(resource => resource.destroy());\n this.managedResources = [];\n }\n\n override getBounds(): [number[], number[]] | null {\n return this.bounds;\n }\n\n // Expose model methods\n draw(renderPass: RenderPass) {\n // Return value indicates if something was actually drawn\n return this.model.draw(renderPass);\n }\n}\n\nfunction getInstancedScenegraphBounds(\n bounds: ScenegraphBounds,\n instanceMatrices: readonly NumericArray[]\n): ScenegraphBounds | null {\n const instancedBounds = makeEmptyScenegraphBounds();\n\n for (const instanceMatrix of instanceMatrices) {\n expandScenegraphBounds(instancedBounds, bounds, instanceMatrix);\n }\n\n return areScenegraphBoundsDefined(instancedBounds) ? instancedBounds : null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n// import type {GeometryType} from '../geometry/geometry-type';\n\nexport type CubeGeometryProps = {\n id?: string;\n indices?: boolean;\n attributes?: any;\n};\n\nexport class CubeGeometry extends Geometry {\n constructor(props: CubeGeometryProps = {}) {\n const {id = uid('cube-geometry'), indices = true} = props;\n super(\n indices\n ? {\n ...props,\n id,\n topology: 'triangle-list',\n indices: {size: 1, value: CUBE_INDICES},\n attributes: {...ATTRIBUTES, ...props.attributes}\n }\n : {\n ...props,\n id,\n topology: 'triangle-list',\n indices: undefined,\n attributes: {...NON_INDEXED_ATTRIBUTES, ...props.attributes}\n }\n );\n }\n}\n\n// biome-ignore format: preserve layout\nconst CUBE_INDICES = new Uint16Array([\n 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13,\n 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23\n]);\n\n// biome-ignore format: preserve layout\nconst CUBE_POSITIONS = new Float32Array([\n -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1,\n -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1,\n -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1,\n -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1,\n 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1,\n -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1\n]);\n\n// TODO - could be Uint8\n// biome-ignore format: preserve layout\nconst CUBE_NORMALS = new Float32Array([\n // Front face\n 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,\n // Back face\n 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1,\n // Top face\n 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,\n // Bottom face\n 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,\n // Right face\n 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,\n // Left face\n -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0\n]);\n\n// biome-ignore format: preserve layout\nconst CUBE_TEX_COORDS = new Float32Array([\n // Front face\n 0, 0, 1, 0, 1, 1, 0, 1,\n // Back face\n 1, 0, 1, 1, 0, 1, 0, 0,\n // Top face\n 0, 1, 0, 0, 1, 0, 1, 1,\n // Bottom face\n 1, 1, 0, 1, 0, 0, 1, 0,\n // Right face\n 1, 0, 1, 1, 0, 1, 0, 0,\n // Left face\n 0, 0, 1, 0, 1, 1, 0, 1\n]);\n\n// biome-ignore format: preserve layout\nconst CUBE_FACE_INDICES = new Uint32Array([\n 0, 0, 0, 0,\n 1, 1, 1, 1,\n 2, 2, 2, 2,\n 3, 3, 3, 3,\n 4, 4, 4, 4,\n 5, 5, 5, 5\n]);\n\n// float4 position\n// biome-ignore format: preserve layout\nexport const CUBE_NON_INDEXED_POSITIONS = new Float32Array([\n 1, -1, 1,\n -1, -1, 1,\n -1, -1, -1,\n 1, -1, -1,\n 1, -1, 1,\n -1, -1, -1,\n\n 1, 1, 1,\n 1, -1, 1,\n 1, -1, -1,\n 1, 1, -1,\n 1, 1, 1,\n 1, -1, -1,\n\n -1, 1, 1,\n 1, 1, 1,\n 1, 1, -1,\n -1, 1, -1,\n -1, 1, 1,\n 1, 1, -1,\n\n -1, -1, 1,\n -1, 1, 1,\n -1, 1, -1,\n -1, -1, -1,\n -1, -1, 1,\n -1, 1, -1,\n\n 1, 1, 1,\n -1, 1, 1,\n -1, -1, 1,\n -1, -1, 1,\n 1, -1, 1,\n 1, 1, 1,\n\n 1, -1, -1,\n -1, -1, -1,\n -1, 1, -1,\n 1, 1, -1,\n 1, -1, -1,\n -1, 1, -1,\n]);\n\n// float2 uv,\n// biome-ignore format: preserve layout\nexport const CUBE_NON_INDEXED_TEX_COORDS = new Float32Array([\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 0, 0,\n 1, 0,\n 1, 1,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n]);\n\n// float4 color\n// biome-ignore format: preserve layout\nexport const CUBE_NON_INDEXED_COLORS = new Float32Array([\n 1, 0, 1, 1,\n 0, 0, 1, 1,\n 0, 0, 0, 1,\n 1, 0, 0, 1,\n 1, 0, 1, 1,\n 0, 0, 0, 1,\n\n 1, 1, 1, 1,\n 1, 0, 1, 1,\n 1, 0, 0, 1,\n 1, 1, 0, 1,\n 1, 1, 1, 1,\n 1, 0, 0, 1,\n\n 0, 1, 1, 1,\n 1, 1, 1, 1,\n 1, 1, 0, 1,\n 0, 1, 0, 1,\n 0, 1, 1, 1,\n 1, 1, 0, 1,\n\n 0, 0, 1, 1,\n 0, 1, 1, 1,\n 0, 1, 0, 1,\n 0, 0, 0, 1,\n 0, 0, 1, 1,\n 0, 1, 0, 1,\n\n 1, 1, 1, 1,\n 0, 1, 1, 1,\n 0, 0, 1, 1,\n 0, 0, 1, 1,\n 1, 0, 1, 1,\n 1, 1, 1, 1,\n\n 1, 0, 0, 1,\n 0, 0, 0, 1,\n 0, 1, 0, 1,\n 1, 1, 0, 1,\n 1, 0, 0, 1,\n 0, 1, 0, 1,\n]);\n\n// biome-ignore format: preserve layout\nexport const CUBE_NON_INDEXED_FACE_INDICES = new Uint32Array([\n 3, 3, 3, 3, 3, 3,\n 4, 4, 4, 4, 4, 4,\n 2, 2, 2, 2, 2, 2,\n 5, 5, 5, 5, 5, 5,\n 0, 0, 0, 0, 0, 0,\n 1, 1, 1, 1, 1, 1\n]);\n\nconst ATTRIBUTES = {\n POSITION: {size: 3, value: CUBE_POSITIONS},\n NORMAL: {size: 3, value: CUBE_NORMALS},\n TEXCOORD_0: {size: 2, value: CUBE_TEX_COORDS},\n faceIndex: {size: 1, value: CUBE_FACE_INDICES}\n};\n\nconst NON_INDEXED_ATTRIBUTES = {\n POSITION: {size: 3, value: CUBE_NON_INDEXED_POSITIONS},\n // NORMAL: {size: 3, value: CUBE_NON_INDEXED_NORMALS},\n TEXCOORD_0: {size: 2, value: CUBE_NON_INDEXED_TEX_COORDS},\n COLOR_0: {size: 3, value: CUBE_NON_INDEXED_COLORS},\n faceIndex: {size: 1, value: CUBE_NON_INDEXED_FACE_INDICES}\n};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TruncatedConeGeometryProps} from './truncated-cone-geometry';\nimport {TruncatedConeGeometry} from './truncated-cone-geometry';\nimport {uid} from '../utils/uid';\n\nexport type CylinderGeometryProps = Omit<\n TruncatedConeGeometryProps,\n 'topRadius' | 'bottomRadius'\n> & {\n id?: string;\n radius?: number;\n attributes?: any;\n};\n\nexport class CylinderGeometry extends TruncatedConeGeometry {\n constructor(props: CylinderGeometryProps = {}) {\n const {id = uid('cylinder-geometry'), radius = 1} = props;\n super({\n ...props,\n id,\n bottomRadius: radius,\n topRadius: radius\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Vector3} from '@math.gl/core';\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\n/* eslint-disable comma-spacing, max-statements, complexity */\n\nconst ICO_POSITIONS = [-1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, -1, 0, 1, 0, 0];\nconst ICO_INDICES = [3, 4, 5, 3, 5, 1, 3, 1, 0, 3, 0, 4, 4, 0, 2, 4, 2, 5, 2, 0, 1, 5, 2, 1];\n\nexport type IcoSphereGeometryProps = {\n id?: string;\n radius?: number;\n iterations?: number;\n attributes?: any;\n};\n\nexport class IcoSphereGeometry extends Geometry {\n constructor(props: IcoSphereGeometryProps = {}) {\n const {id = uid('ico-sphere-geometry')} = props;\n const {indices, attributes} = tesselateIcosaHedron(props);\n super({\n ...props,\n id,\n topology: 'triangle-list',\n indices,\n attributes: {...attributes, ...props.attributes}\n });\n }\n}\n\nfunction tesselateIcosaHedron(props: IcoSphereGeometryProps) {\n const {iterations = 0} = props;\n\n const PI = Math.PI;\n const PI2 = PI * 2;\n\n const positions = [...ICO_POSITIONS];\n let indices = [...ICO_INDICES];\n\n positions.push();\n indices.push();\n\n const getMiddlePoint = (() => {\n const pointMemo: Record<string, number> = {};\n\n return (i1: number, i2: number) => {\n i1 *= 3;\n i2 *= 3;\n const mini = i1 < i2 ? i1 : i2;\n const maxi = i1 > i2 ? i1 : i2;\n const key = `${mini}|${maxi}`;\n\n if (key in pointMemo) {\n return pointMemo[key];\n }\n\n const x1 = positions[i1];\n const y1 = positions[i1 + 1];\n const z1 = positions[i1 + 2];\n const x2 = positions[i2];\n const y2 = positions[i2 + 1];\n const z2 = positions[i2 + 2];\n let xm = (x1 + x2) / 2;\n let ym = (y1 + y2) / 2;\n let zm = (z1 + z2) / 2;\n const len = Math.sqrt(xm * xm + ym * ym + zm * zm);\n\n xm /= len;\n ym /= len;\n zm /= len;\n\n positions.push(xm, ym, zm);\n\n const pointIndex = positions.length / 3 - 1;\n pointMemo[key] = pointIndex;\n return pointIndex;\n };\n })();\n\n for (let i = 0; i < iterations; i++) {\n const indices2: number[] = [];\n for (let j = 0; j < indices.length; j += 3) {\n const a = getMiddlePoint(indices[j + 0], indices[j + 1]);\n const b = getMiddlePoint(indices[j + 1], indices[j + 2]);\n const c = getMiddlePoint(indices[j + 2], indices[j + 0]);\n\n indices2.push(c, indices[j + 0], a, a, indices[j + 1], b, b, indices[j + 2], c, a, b, c);\n }\n indices = indices2;\n }\n\n // Calculate texCoords and normals\n const normals = new Array(positions.length);\n const texCoords = new Array((positions.length / 3) * 2);\n\n const l = indices.length;\n for (let i = l - 3; i >= 0; i -= 3) {\n const i1 = indices[i + 0];\n const i2 = indices[i + 1];\n const i3 = indices[i + 2];\n const in1 = i1 * 3;\n const in2 = i2 * 3;\n const in3 = i3 * 3;\n const iu1 = i1 * 2;\n const iu2 = i2 * 2;\n const iu3 = i3 * 2;\n const x1 = positions[in1 + 0];\n const y1 = positions[in1 + 1];\n const z1 = positions[in1 + 2];\n const theta1 = Math.acos(z1 / Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1));\n const phi1 = Math.atan2(y1, x1) + PI;\n const v1 = theta1 / PI;\n const u1 = 1 - phi1 / PI2;\n const x2 = positions[in2 + 0];\n const y2 = positions[in2 + 1];\n const z2 = positions[in2 + 2];\n const theta2 = Math.acos(z2 / Math.sqrt(x2 * x2 + y2 * y2 + z2 * z2));\n const phi2 = Math.atan2(y2, x2) + PI;\n const v2 = theta2 / PI;\n const u2 = 1 - phi2 / PI2;\n const x3 = positions[in3 + 0];\n const y3 = positions[in3 + 1];\n const z3 = positions[in3 + 2];\n const theta3 = Math.acos(z3 / Math.sqrt(x3 * x3 + y3 * y3 + z3 * z3));\n const phi3 = Math.atan2(y3, x3) + PI;\n const v3 = theta3 / PI;\n const u3 = 1 - phi3 / PI2;\n const vec1 = [x3 - x2, y3 - y2, z3 - z2];\n const vec2 = [x1 - x2, y1 - y2, z1 - z2];\n const normal = new Vector3(vec1).cross(vec2).normalize();\n let newIndex;\n\n if (\n (u1 === 0 || u2 === 0 || u3 === 0) &&\n (u1 === 0 || u1 > 0.5) &&\n (u2 === 0 || u2 > 0.5) &&\n (u3 === 0 || u3 > 0.5)\n ) {\n positions.push(positions[in1 + 0], positions[in1 + 1], positions[in1 + 2]);\n newIndex = positions.length / 3 - 1;\n indices.push(newIndex);\n texCoords[newIndex * 2 + 0] = 1;\n texCoords[newIndex * 2 + 1] = v1;\n normals[newIndex * 3 + 0] = normal.x;\n normals[newIndex * 3 + 1] = normal.y;\n normals[newIndex * 3 + 2] = normal.z;\n\n positions.push(positions[in2 + 0], positions[in2 + 1], positions[in2 + 2]);\n newIndex = positions.length / 3 - 1;\n indices.push(newIndex);\n texCoords[newIndex * 2 + 0] = 1;\n texCoords[newIndex * 2 + 1] = v2;\n normals[newIndex * 3 + 0] = normal.x;\n normals[newIndex * 3 + 1] = normal.y;\n normals[newIndex * 3 + 2] = normal.z;\n\n positions.push(positions[in3 + 0], positions[in3 + 1], positions[in3 + 2]);\n newIndex = positions.length / 3 - 1;\n indices.push(newIndex);\n texCoords[newIndex * 2 + 0] = 1;\n texCoords[newIndex * 2 + 1] = v3;\n normals[newIndex * 3 + 0] = normal.x;\n normals[newIndex * 3 + 1] = normal.y;\n normals[newIndex * 3 + 2] = normal.z;\n }\n\n normals[in1 + 0] = normals[in2 + 0] = normals[in3 + 0] = normal.x;\n normals[in1 + 1] = normals[in2 + 1] = normals[in3 + 1] = normal.y;\n normals[in1 + 2] = normals[in2 + 2] = normals[in3 + 2] = normal.z;\n\n texCoords[iu1 + 0] = u1;\n texCoords[iu1 + 1] = v1;\n\n texCoords[iu2 + 0] = u2;\n texCoords[iu2 + 1] = v2;\n\n texCoords[iu3 + 0] = u3;\n texCoords[iu3 + 1] = v3;\n }\n\n return {\n indices: {size: 1, value: new Uint16Array(indices)},\n attributes: {\n POSITION: {size: 3, value: new Float32Array(positions)},\n NORMAL: {size: 3, value: new Float32Array(normals)},\n TEXCOORD_0: {size: 2, value: new Float32Array(texCoords)}\n }\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geometry} from '../geometry/geometry';\nimport {unpackIndexedGeometry} from '../geometry/geometry-utils';\nimport {uid} from '../utils/uid';\n\nexport type PlaneGeometryProps = {\n id?: string;\n radius?: number;\n attributes?: any;\n type?: 'x,y' | 'x,z' | 'y,z';\n offset?: number;\n flipCull?: boolean;\n unpack?: boolean;\n xlen?: number;\n ylen?: number;\n zlen?: number;\n nx?: number;\n ny?: number;\n nz?: number;\n};\n\n// Primitives inspired by TDL http://code.google.com/p/webglsamples/,\n// copyright 2011 Google Inc. new BSD License\n// (http://www.opensource.org/licenses/bsd-license.php).\nexport class PlaneGeometry extends Geometry {\n constructor(props: PlaneGeometryProps = {}) {\n const {id = uid('plane-geometry')} = props;\n\n const {indices, attributes} = tesselatePlane(props);\n super({\n ...props,\n id,\n topology: 'triangle-list',\n indices,\n attributes: {...attributes, ...props.attributes}\n });\n }\n}\n\n/* eslint-disable complexity, max-statements */\nfunction tesselatePlane(props: any) {\n const {type = 'x,y', offset = 0, flipCull = false, unpack = false} = props;\n\n const coords = type.split(',');\n // width, height\n let c1len = props[`${coords[0]}len`] || 1;\n const c2len = props[`${coords[1]}len`] || 1;\n // subdivisionsWidth, subdivisionsDepth\n const subdivisions1 = props[`n${coords[0]}`] || 1;\n const subdivisions2 = props[`n${coords[1]}`] || 1;\n const numVertices = (subdivisions1 + 1) * (subdivisions2 + 1);\n\n const positions = new Float32Array(numVertices * 3);\n const normals = new Float32Array(numVertices * 3);\n const texCoords = new Float32Array(numVertices * 2);\n\n if (flipCull) {\n c1len = -c1len;\n }\n\n let i2 = 0;\n let i3 = 0;\n for (let z = 0; z <= subdivisions2; z++) {\n for (let x = 0; x <= subdivisions1; x++) {\n const u = x / subdivisions1;\n const v = z / subdivisions2;\n texCoords[i2 + 0] = flipCull ? 1 - u : u;\n texCoords[i2 + 1] = v;\n\n switch (type) {\n case 'x,y':\n positions[i3 + 0] = c1len * u - c1len * 0.5;\n positions[i3 + 1] = c2len * v - c2len * 0.5;\n positions[i3 + 2] = offset;\n\n normals[i3 + 0] = 0;\n normals[i3 + 1] = 0;\n normals[i3 + 2] = flipCull ? 1 : -1;\n break;\n\n case 'x,z':\n positions[i3 + 0] = c1len * u - c1len * 0.5;\n positions[i3 + 1] = offset;\n positions[i3 + 2] = c2len * v - c2len * 0.5;\n\n normals[i3 + 0] = 0;\n normals[i3 + 1] = flipCull ? 1 : -1;\n normals[i3 + 2] = 0;\n break;\n\n case 'y,z':\n positions[i3 + 0] = offset;\n positions[i3 + 1] = c1len * u - c1len * 0.5;\n positions[i3 + 2] = c2len * v - c2len * 0.5;\n\n normals[i3 + 0] = flipCull ? 1 : -1;\n normals[i3 + 1] = 0;\n normals[i3 + 2] = 0;\n break;\n\n default:\n throw new Error('PlaneGeometry: unknown type');\n }\n\n i2 += 2;\n i3 += 3;\n }\n }\n\n const numVertsAcross = subdivisions1 + 1;\n const indices = new Uint16Array(subdivisions1 * subdivisions2 * 6);\n\n for (let z = 0; z < subdivisions2; z++) {\n for (let x = 0; x < subdivisions1; x++) {\n const index = (z * subdivisions1 + x) * 6;\n // Make triangle 1 of quad.\n indices[index + 0] = (z + 0) * numVertsAcross + x;\n indices[index + 1] = (z + 1) * numVertsAcross + x;\n indices[index + 2] = (z + 0) * numVertsAcross + x + 1;\n\n // Make triangle 2 of quad.\n indices[index + 3] = (z + 1) * numVertsAcross + x;\n indices[index + 4] = (z + 1) * numVertsAcross + x + 1;\n indices[index + 5] = (z + 0) * numVertsAcross + x + 1;\n }\n }\n\n const geometry = {\n indices: {size: 1, value: indices},\n attributes: {\n POSITION: {size: 3, value: positions},\n NORMAL: {size: 3, value: normals},\n TEXCOORD_0: {size: 2, value: texCoords}\n }\n };\n\n // Optionally, unpack indexed geometry\n return unpack ? unpackIndexedGeometry(geometry) : geometry;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Creates a deterministic pseudorandom number generator */\nexport function makeRandomGenerator(): () => number {\n let s = 1;\n let c = 1;\n return () => {\n s = Math.sin(c * 17.23);\n c = Math.cos(s * 27.92);\n return fract(Math.abs(s * c) * 1432.71);\n };\n}\n\nfunction fract(n: number): number {\n return n - Math.floor(n);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nlet pathPrefix = '';\n\n/**\n * Set a relative path prefix\n */\nexport function setPathPrefix(prefix: string) {\n pathPrefix = prefix;\n}\n\n/** @internal */\nexport function _resolveLoadFileUrl(url: string): string {\n return isAbsoluteLoadFileUrl(url) ? url : pathPrefix + url;\n}\n\n/**\n * Loads ImageBitmap asynchronously. Respects setPathPrefix.\n * image.crossOrigin can be set via opts.crossOrigin, default to 'anonymous'\n * @returns a promise tracking the load\n */\nexport async function loadImageBitmap(\n url: string,\n opts?: {crossOrigin?: string} & ImageBitmapOptions\n): Promise<ImageBitmap> {\n const image = new Image();\n const resolvedUrl = _resolveLoadFileUrl(url);\n image.crossOrigin = opts?.crossOrigin || 'anonymous';\n image.src = resolvedUrl;\n\n try {\n await image.decode();\n } catch (error) {\n throw createImageBitmapLoadError('decode', resolvedUrl, error);\n }\n\n try {\n return opts ? await createImageBitmap(image, opts) : await createImageBitmap(image);\n } catch (error) {\n throw createImageBitmapLoadError('create', resolvedUrl, error);\n }\n}\n\n/**\n * Loads image asynchronously. Respects setPathPrefix.\n * image.crossOrigin can be set via opts.crossOrigin, default to 'anonymous'\n * @returns a promise tracking the load\n * @deprecated Use `loadImageBitmap()` unless you are supporting old versions of Safari.\n */\nexport async function loadImage(\n url: string,\n opts?: {crossOrigin?: string}\n): Promise<HTMLImageElement> {\n return await new Promise((resolve, reject) => {\n try {\n const image = new Image();\n const resolvedUrl = _resolveLoadFileUrl(url);\n image.onload = () => resolve(image);\n image.onerror = () => reject(new Error(`Could not load image ${resolvedUrl}.`));\n image.crossOrigin = opts?.crossOrigin || 'anonymous';\n image.src = resolvedUrl;\n } catch (error) {\n reject(error);\n }\n });\n}\n\nfunction createImageBitmapLoadError(\n phase: 'decode' | 'create',\n resolvedUrl: string,\n error: unknown\n): Error {\n const reason = error instanceof Error ? error.message : String(error);\n const message =\n phase === 'decode'\n ? `Could not decode source image \"${resolvedUrl}\": ${reason}`\n : `Could not create ImageBitmap from decoded image \"${resolvedUrl}\": ${reason}`;\n return new Error(message, {cause: error});\n}\nfunction isAbsoluteLoadFileUrl(url: string): boolean {\n return url.startsWith('/') || /^[a-z][a-z\\d+\\-.]*:/i.test(url);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, ExternalTexture, ResourceProps, Sampler, SamplerProps} from '@luma.gl/core';\nimport {Texture, assert} from '@luma.gl/core';\nimport {uid} from '../utils/uid';\nimport type {TextureBindingLayout, TextureBindingSource} from './texture-binding-source';\n\n/** Properties for a live video binding source. */\nexport type VideoTextureProps = Pick<ResourceProps, 'id'> & {\n /** Caller-owned live video source followed by this binding source. */\n source: HTMLVideoElement | VideoFrame;\n /** Color space requested for copied or imported video data. */\n colorSpace?: 'srgb';\n /** Default sampler used by copied and native external bindings. */\n sampler?: Sampler | SamplerProps;\n};\n\n/**\n * Live video binding source.\n *\n * GLSL `sampler2D` and WGSL `texture_2d` bindings resolve to copied luma textures.\n * WGSL `texture_external` bindings resolve to native WebGPU external textures.\n */\nexport class VideoTexture implements TextureBindingSource {\n /** Device used to create copied and native external texture bindings. */\n readonly device: Device;\n /** Stable resource identifier used in loading and debug messages. */\n readonly id: string;\n\n /** Whether this video binding source has been destroyed. */\n destroyed = false;\n /** Monotonic binding generation advanced when concrete draw bindings may need recreation. */\n generation = 0;\n\n private _source: HTMLVideoElement | VideoFrame;\n private _colorSpace: 'srgb';\n private _sampler: Sampler | SamplerProps;\n private _isReady = false;\n private _updateTimestamp: number;\n private _sourceVersion = 0;\n private _sourceFrameToken: unknown = null;\n private _texture: Texture | null = null;\n private _textureFrameToken: unknown = undefined;\n private _externalTexture: ExternalTexture | null = null;\n\n /** Current caller-owned live video source. */\n get source(): HTMLVideoElement | VideoFrame {\n return this._source;\n }\n\n /** Whether the current source exposes dimensions and a current frame. */\n get isReady(): boolean {\n this._observeSource();\n return this._isReady;\n }\n\n /** Device timestamp of the most recent source content or binding identity update. */\n get updateTimestamp(): number {\n this._observeSource();\n return this._updateTimestamp;\n }\n\n /** Resource label used by debug output. */\n get [Symbol.toStringTag]() {\n return 'VideoTexture';\n }\n\n /** Formats the current source dimensions and readiness for debug output. */\n toString(): string {\n const size = getVideoTextureSourceSize(this._source);\n return `VideoTexture:\"${this.id}\":${size.width}x${size.height}px:(${this._isReady ? 'ready' : 'loading...'})`;\n }\n\n /**\n * Creates a live video binding source.\n * @param device Device that resolves copied or native external bindings.\n * @param props Live video source and copied texture options.\n */\n constructor(device: Device, props: VideoTextureProps) {\n // Error: VideoTexture source must be an HTMLVideoElement or VideoFrame.\n assert(isHTMLVideoElementSource(props?.source) || isVideoFrameSource(props?.source));\n\n this.device = device;\n this.id = props.id || uid('video-texture');\n this._source = props.source;\n this._colorSpace = props.colorSpace ?? 'srgb';\n this._sampler = props.sampler ?? {};\n this._updateTimestamp = this.device.incrementTimestamp();\n\n this.setSource(props.source);\n }\n\n /**\n * Replaces the caller-owned video source and invalidates resolved bindings.\n * @param source Next caller-owned video source to follow.\n */\n setSource(source: HTMLVideoElement | VideoFrame): void {\n // Error: VideoTexture source must be an HTMLVideoElement or VideoFrame.\n assert(isHTMLVideoElementSource(source) || isVideoFrameSource(source));\n\n this._destroyExternalTexture();\n this._source = source;\n this._sourceVersion++;\n this._sourceFrameToken = null;\n this._textureFrameToken = undefined;\n this._observeSource();\n this._touchGeneration();\n }\n\n /**\n * Resolves one reflected shader texture slot for the current video frame.\n * @param bindingLayout Reflected `texture` or `external-texture` shader slot.\n * @returns A copied texture, native external texture, or `null` while unavailable.\n */\n resolveTextureBinding(bindingLayout: TextureBindingLayout): Texture | ExternalTexture | null {\n this._observeSource();\n if (!this._isReady || this.destroyed) {\n return null;\n }\n\n if (bindingLayout.type === 'external-texture' && this.device.type === 'webgpu') {\n return this._createNativeExternalTexture();\n }\n\n return this._resolveCopiedTexture();\n }\n\n /**\n * Replaces the default sampler used by copied and native external bindings.\n * @param sampler Sampler instance or sampler properties to use for future resolutions.\n */\n setSampler(sampler: Sampler | SamplerProps): void {\n this._sampler = sampler;\n this._texture?.setSampler(sampler);\n this._externalTexture?.setSampler?.(sampler);\n this._touchGeneration();\n }\n\n /** Releases owned copied/external bindings without closing the caller-owned source. */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this._destroyExternalTexture();\n this._texture?.destroy();\n this._texture = null;\n this._textureFrameToken = undefined;\n this._isReady = false;\n this.destroyed = true;\n this._touchGeneration();\n }\n\n /**\n * Resolves and uploads the copied texture variant for the current source frame.\n * @returns Copied texture containing the current observed frame.\n */\n private _resolveCopiedTexture(): Texture {\n const texture = this._getOrCreateCopiedTexture();\n if (!Object.is(this._textureFrameToken, this._sourceFrameToken)) {\n // A copy failure usually means that the video is not ready or CORS-accessible, or that the\n // caller closed the current VideoFrame before draw binding resolution completed.\n texture.copyExternalImage({\n image: this._source,\n colorSpace: this._colorSpace\n });\n this._textureFrameToken = this._sourceFrameToken;\n }\n return texture;\n }\n\n /**\n * Returns an existing size-compatible copied texture or creates one lazily.\n * @returns Copied texture allocated for the current source dimensions.\n */\n private _getOrCreateCopiedTexture(): Texture {\n const size = this._getResolvedSize();\n const currentTexture = this._texture;\n if (\n currentTexture &&\n currentTexture.width === size.width &&\n currentTexture.height === size.height\n ) {\n return currentTexture;\n }\n\n currentTexture?.destroy();\n\n const texture = this.device.createTexture({\n id: `${this.id}-texture`,\n width: size.width,\n height: size.height,\n format: 'rgba8unorm',\n usage: Texture.SAMPLE | Texture.COPY_DST,\n mipLevels: 1,\n sampler: this._sampler\n });\n this._texture = texture;\n this._textureFrameToken = undefined;\n this._touchGeneration();\n return texture;\n }\n\n /**\n * Acquires one native WebGPU external texture binding.\n * @returns Fresh acquired external texture.\n */\n private _createNativeExternalTexture(): ExternalTexture {\n // A WebGPU external-texture slot cannot accept a copied Texture fallback. Callers that need\n // the portable copied path must declare texture_2d<f32> in the shader instead.\n this._destroyExternalTexture();\n this._externalTexture = this.device.createExternalTexture({\n id: `${this.id}-external`,\n source: this._source,\n colorSpace: this._colorSpace,\n sampler: this._sampler\n });\n this.generation++;\n return this._externalTexture;\n }\n\n /** Releases the current acquired external texture wrapper. */\n private _destroyExternalTexture(): void {\n this._externalTexture?.destroy();\n this._externalTexture = null;\n }\n\n /**\n * Resolves current copied texture dimensions.\n * @returns Positive dimensions for the current source frame.\n */\n private _getResolvedSize(): {width: number; height: number} {\n const size = getVideoTextureSourceSize(this._source);\n // Error: VideoTexture source has no current frame size.\n assert(size.width > 0 && size.height > 0);\n return size;\n }\n\n /** Observes current source readiness and frame identity before binding resolution. */\n private _observeSource(): void {\n if (this.destroyed) {\n return;\n }\n\n const isReady = isVideoTextureSourceReady(this._source);\n if (isReady !== this._isReady) {\n this._isReady = isReady;\n this._touch();\n }\n\n if (!isReady) {\n return;\n }\n\n const frameToken = getVideoTextureSourceFrameToken(this._source, this._sourceVersion);\n if (!Object.is(frameToken, this._sourceFrameToken)) {\n this._sourceFrameToken = frameToken;\n this._touch();\n }\n }\n\n /** Advances the device timestamp after source content or readiness changes. */\n private _touch(): void {\n this._updateTimestamp = this.device.incrementTimestamp();\n }\n\n /** Advances binding generation and timestamp after binding identity can change. */\n private _touchGeneration(): void {\n this.generation++;\n this._touch();\n }\n}\n\n/** Returns whether a video source exposes HTML video element playback state. */\nfunction isHTMLVideoElementSource(source: unknown): source is HTMLVideoElement {\n if (!source || typeof source !== 'object') {\n return false;\n }\n\n return (\n (typeof HTMLVideoElement !== 'undefined' && source instanceof HTMLVideoElement) ||\n ('videoWidth' in source &&\n 'videoHeight' in source &&\n 'readyState' in source &&\n 'currentTime' in source)\n );\n}\n\n/** Returns whether a video source exposes VideoFrame dimensions and timestamp. */\nfunction isVideoFrameSource(source: unknown): source is VideoFrame {\n if (!source || typeof source !== 'object') {\n return false;\n }\n\n return (\n (typeof VideoFrame !== 'undefined' && source instanceof VideoFrame) ||\n ('displayWidth' in source &&\n 'displayHeight' in source &&\n 'timestamp' in source &&\n !('videoWidth' in source))\n );\n}\n\n/** Returns whether a video source exposes dimensions and a current sampleable frame. */\nfunction isVideoTextureSourceReady(source: HTMLVideoElement | VideoFrame): boolean {\n const size = getVideoTextureSourceSize(source);\n if (size.width <= 0 || size.height <= 0) {\n return false;\n }\n return isHTMLVideoElementSource(source) ? source.readyState >= 2 : true;\n}\n\n/** Returns current sampleable source dimensions. */\nfunction getVideoTextureSourceSize(source: HTMLVideoElement | VideoFrame): {\n width: number;\n height: number;\n} {\n if (isHTMLVideoElementSource(source)) {\n return {width: source.videoWidth, height: source.videoHeight};\n }\n return {width: source.displayWidth, height: source.displayHeight};\n}\n\n/** Returns the source token used to detect video frame replacement or advancement. */\nfunction getVideoTextureSourceFrameToken(\n source: HTMLVideoElement | VideoFrame,\n sourceVersion: number\n): unknown {\n if (isHTMLVideoElementSource(source)) {\n return `${sourceVersion}:${source.currentTime}:${source.videoWidth}x${source.videoHeight}`;\n }\n return `${sourceVersion}:${source.timestamp}:${source.displayWidth}x${source.displayHeight}`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CommandEncoder, TextureFormatColor} from '@luma.gl/core';\nimport {Device, Framebuffer, RenderPass, Texture} from '@luma.gl/core';\nimport type {\n ShaderPass,\n ShaderPassInputSource,\n ShaderPassPipeline,\n ShaderPassRenderTarget\n} from '@luma.gl/shadertools';\nimport {initializeShaderModule} from '@luma.gl/shadertools';\nimport {ShaderInputs} from '../shader-inputs';\nimport {DynamicTexture} from '../dynamic-texture/dynamic-texture';\nimport type {TextureBindingSource} from '../dynamic-texture/texture-binding-source';\nimport {ClipSpace} from '../models/clip-space';\nimport {SwapFramebuffers} from '../compute/swap';\nimport {BackgroundTextureModel} from '../models/billboard-texture-model';\n\nimport {getFragmentShaderForRenderPass} from './get-fragment-shader';\nimport {textureTransform} from './texture-transform-module';\n\ntype ShaderPassLike = ShaderPass | ShaderPassPipeline;\ntype ShaderSubPass = NonNullable<ShaderPass['passes']>[0];\n\ntype EffectiveSubPass = {\n ownerName: string;\n shaderPass: ShaderPass;\n subPassRenderer: SubPassRenderer;\n inputs?: Partial<Record<string, ShaderPassInputSource<string>>>;\n output?: 'previous' | string;\n uniforms?: Record<string, unknown>;\n};\n\ntype ManagedRenderTarget = {\n name: string;\n spec: ShaderPassRenderTarget;\n texture: Texture;\n framebuffer: Framebuffer;\n historyTexture?: Texture;\n historyFramebuffer?: Framebuffer;\n historyInitialized: boolean;\n writtenThisFrame: boolean;\n};\n\nconst RESERVED_RENDER_TARGET_NAMES = new Set(['original', 'previous']);\n\n/** Construction props for {@link ShaderPassRenderer}. */\nexport type ShaderPassRendererProps = {\n /** List of ShaderPasses or ShaderPassPipelines to apply to the sourceTexture */\n shaderPasses: ShaderPassLike[];\n /** Optional typed ShaderInputs object for setting uniforms */\n shaderInputs?: ShaderInputs;\n /** Format of the shared previous-chain textures. Defaults to the canvas-preferred format. */\n colorFormat?: TextureFormatColor;\n /** Flip source and presentation sampling vertically. Defaults to true on WebGPU. */\n flipY?: boolean;\n};\n\n/** Source texture accepted by {@link ShaderPassRenderer}. */\nexport type ShaderPassSourceTexture = DynamicTexture | Texture;\n/** Binding accepted by shader pass inputs, including deferred texture binding sources. */\nexport type ShaderPassBinding = Binding | TextureBindingSource;\n\n/** Per-frame inputs accepted by {@link ShaderPassRenderer}. */\nexport type ShaderPassRendererRenderOptions = {\n sourceTexture: ShaderPassSourceTexture;\n uniforms?: Record<string, Record<string, unknown>>;\n bindings?: Record<string, ShaderPassBinding>;\n /** Invalidates all persistent render targets before rendering this frame. */\n resetHistory?: boolean;\n};\n\n/**\n * Runs one or more shader passes against a source texture.\n *\n * The renderer owns:\n * - a shared ping-pong pair for the logical `previous` chain\n * - any named render targets declared by `ShaderPassPipeline`\n * - a fullscreen model used both to seed the chain and to present to the screen\n *\n * Per-draw `uniforms` and `bindings` passed to `renderToTexture()` or `renderToScreen()` are\n * merged on top of the renderer's `shaderInputs`, which lets callers reuse one renderer instance\n * while varying pass inputs frame to frame.\n */\nexport class ShaderPassRenderer {\n device: Device;\n shaderInputs: ShaderInputs;\n passRenderers: PassRenderer[];\n swapFramebuffers: SwapFramebuffers;\n textureModel: BackgroundTextureModel;\n\n constructor(device: Device, props: ShaderPassRendererProps) {\n this.device = device;\n\n const executableShaderPasses = getExecutableShaderPasses(props.shaderPasses);\n executableShaderPasses.map(shaderPass => initializeShaderModule(shaderPass));\n\n const modules = executableShaderPasses.reduce(\n (object, shaderPass) => ({...object, [shaderPass.name]: shaderPass}),\n {}\n );\n this.shaderInputs = props.shaderInputs || new ShaderInputs(modules);\n\n const size = device.getCanvasContext().getDrawingBufferSize();\n this.swapFramebuffers = new SwapFramebuffers(device, {\n colorAttachments: [props.colorFormat || device.preferredColorFormat],\n width: size[0],\n height: size[1]\n });\n\n this.textureModel = new BackgroundTextureModel(device, {\n backgroundTexture: this.swapFramebuffers.current.colorAttachments[0].texture,\n flipY: props.flipY ?? device.type === 'webgpu'\n });\n\n const flipY = props.flipY ?? device.type === 'webgpu';\n this.passRenderers = props.shaderPasses.map(\n shaderPass => new PassRenderer(device, shaderPass, this.shaderInputs, flipY)\n );\n }\n\n /** Destroys resources created by this ShaderPassRenderer */\n destroy() {\n for (const passRenderer of this.passRenderers) {\n passRenderer.destroy();\n }\n this.swapFramebuffers.destroy();\n this.textureModel.destroy();\n }\n\n resize(size?: [width: number, height: number]): void {\n size ||= this.device.getCanvasContext().getDrawingBufferSize();\n this.swapFramebuffers.resize({width: size[0], height: size[1]});\n for (const passRenderer of this.passRenderers) {\n passRenderer.resize(size);\n }\n }\n\n /** Invalidates persistent pipeline targets without destroying their allocations. */\n resetHistory(): void {\n for (const passRenderer of this.passRenderers) {\n passRenderer.resetHistory();\n }\n }\n\n renderToScreen(options: ShaderPassRendererRenderOptions): boolean {\n const outputTexture = this.renderToTexture(options);\n if (!outputTexture) {\n return false;\n }\n\n const framebuffer = this.device\n .getDefaultCanvasContext()\n .getCurrentFramebuffer({depthStencilFormat: false});\n // Prepare fullscreen presentation bindings before opening the render pass so WebGPU\n // uploads stay on the parent command encoder rather than the active render pass encoder.\n this.textureModel.setProps({backgroundTexture: outputTexture});\n this.textureModel.predraw(this.device.commandEncoder);\n const renderPass = this.device.beginRenderPass({\n id: 'shader-pass-renderer-to-screen',\n framebuffer,\n clearDepth: false\n });\n this.textureModel.draw(renderPass);\n renderPass.end();\n return true;\n }\n\n /** Runs the shaderPasses in sequence on the sourceTexture and returns a texture with the results.\n * @returns null if the the sourceTexture has not yet been loaded\n */\n renderToTexture(options: ShaderPassRendererRenderOptions): Texture | null {\n const {sourceTexture} = options;\n if (sourceTexture instanceof DynamicTexture && !sourceTexture.isReady) {\n return null;\n }\n const originalTexture =\n sourceTexture instanceof DynamicTexture ? sourceTexture.texture : sourceTexture;\n\n if (this.passRenderers.length === 0) {\n return originalTexture;\n }\n\n if (options.resetHistory) {\n this.resetHistory();\n }\n\n // Seed the first shared framebuffer with the original source. This normalizes the starting\n // point for later passes so `previous` always refers to a drawing-buffer-sized texture.\n this.textureModel.setProps({backgroundTexture: originalTexture});\n // The seed draw updates fullscreen bind groups, so it must be prepared before the\n // render pass begins to avoid command-encoder locking errors on WebGPU.\n this.textureModel.predraw(this.device.commandEncoder);\n\n const sourceFramebuffer = getSeedFramebuffer(this.swapFramebuffers, originalTexture);\n const seedRenderPass = this.device.beginRenderPass({\n id: 'shader-pass-renderer-seed-source',\n framebuffer: sourceFramebuffer,\n clearColor: [0, 0, 0, 1],\n clearDepth: false\n });\n this.textureModel.draw(seedRenderPass);\n seedRenderPass.end();\n\n let previousFramebuffer: Framebuffer | null = sourceFramebuffer;\n let previousTexture: Texture = getFramebufferTexture(sourceFramebuffer);\n let frameSucceeded = false;\n try {\n for (const passRenderer of this.passRenderers) {\n passRenderer.initializeHistoryTargets(originalTexture, this.textureModel);\n for (const execution of passRenderer.subPassExecutions) {\n const outputName = execution.output || 'previous';\n const outputFramebuffer: Framebuffer =\n outputName === 'previous'\n ? getNextPreviousFramebuffer(this.swapFramebuffers, previousFramebuffer)\n : passRenderer.getOutputFramebuffer(outputName);\n const outputTexture = getFramebufferTexture(outputFramebuffer);\n // Pipeline routing resolves logical input names like `original`, `previous`, or a named\n // render target into concrete textures for this draw.\n const resolvedBindings = passRenderer.resolveBindings({\n execution,\n originalTexture,\n previousTexture,\n outputTexture,\n externalBindings: options.bindings || {}\n });\n // Runtime uniforms are layered last so callers can update a renderer-owned pass without\n // reconstructing it every frame.\n const resolvedUniforms = resolveExecutionUniforms(\n this.shaderInputs,\n execution,\n options.uniforms || {}\n );\n\n execution.subPassRenderer.prepare({\n commandEncoder: this.device.commandEncoder,\n bindings: resolvedBindings,\n textureScale: calculateTextureScale(\n (resolvedBindings['sourceTexture'] as Texture) || previousTexture,\n outputTexture\n ),\n uniforms: resolvedUniforms\n });\n const renderPass = this.device.beginRenderPass({\n id: 'shader-pass-renderer-run-pass',\n framebuffer: outputFramebuffer,\n clearColor: [0, 0, 0, 1],\n clearDepth: 1\n });\n execution.subPassRenderer.draw(renderPass);\n renderPass.end();\n\n if (outputName === 'previous') {\n previousTexture = outputTexture;\n previousFramebuffer = outputFramebuffer;\n } else {\n passRenderer.markTargetWritten(outputName);\n }\n }\n }\n frameSucceeded = true;\n } finally {\n for (const passRenderer of this.passRenderers) {\n passRenderer.finishFrame(frameSucceeded);\n }\n }\n\n return previousTexture;\n }\n}\n\n/** Renders one `ShaderPass` or `ShaderPassPipeline` entry in the chain. */\nclass PassRenderer {\n device: Device;\n shaderInputs: ShaderInputs;\n passDefinition: ShaderPassLike;\n renderTargets: Record<string, ManagedRenderTarget>;\n subPassExecutions: EffectiveSubPass[];\n\n constructor(\n device: Device,\n passDefinition: ShaderPassLike,\n shaderInputs: ShaderInputs,\n flipY: boolean\n ) {\n this.device = device;\n this.shaderInputs = shaderInputs;\n this.passDefinition = passDefinition;\n\n if (isShaderPassPipeline(passDefinition)) {\n validateRenderTargetNames(passDefinition.name, passDefinition.renderTargets || {});\n this.renderTargets = createManagedRenderTargets(device, passDefinition.renderTargets || {});\n this.subPassExecutions = passDefinition.steps.flatMap(step =>\n this.createStepExecutions(passDefinition, step, flipY)\n );\n return;\n }\n\n validateShaderPassDoesNotOwnRenderTargets(passDefinition, passDefinition.name);\n this.renderTargets = {};\n this.subPassExecutions = this.createPassExecutions(passDefinition, {\n ownerName: passDefinition.name,\n flipY\n });\n }\n\n destroy() {\n for (const execution of this.subPassExecutions) {\n execution.subPassRenderer.destroy();\n }\n destroyManagedRenderTargets(this.renderTargets);\n }\n\n resize(size: [width: number, height: number]) {\n resizeManagedRenderTargets(this.device, this.renderTargets, size);\n }\n\n resetHistory(): void {\n for (const renderTarget of Object.values(this.renderTargets)) {\n renderTarget.historyInitialized = false;\n renderTarget.writtenThisFrame = false;\n }\n }\n\n initializeHistoryTargets(originalTexture: Texture, textureModel: BackgroundTextureModel): void {\n for (const renderTarget of Object.values(this.renderTargets)) {\n if (renderTarget.spec.lifetime !== 'history' || renderTarget.historyInitialized) {\n continue;\n }\n const historyFramebuffer = getHistoryFramebuffer(renderTarget);\n const initialize = renderTarget.spec.initialize || {\n clearColor: [0, 0, 0, 0] as [number, number, number, number]\n };\n if (initialize === 'original') {\n textureModel.setProps({backgroundTexture: originalTexture});\n textureModel.predraw(this.device.commandEncoder);\n const renderPass = this.device.beginRenderPass({\n id: `${renderTarget.name}-initialize-history`,\n framebuffer: historyFramebuffer,\n clearColor: [0, 0, 0, 0],\n clearDepth: false\n });\n textureModel.draw(renderPass);\n renderPass.end();\n } else {\n const renderPass = this.device.beginRenderPass({\n id: `${renderTarget.name}-clear-history`,\n framebuffer: historyFramebuffer,\n clearColor: initialize.clearColor,\n clearDepth: false\n });\n renderPass.end();\n }\n renderTarget.historyInitialized = true;\n }\n }\n\n getOutputFramebuffer(name: string): Framebuffer {\n return this.getRenderTarget(name).framebuffer;\n }\n\n markTargetWritten(name: string): void {\n this.getRenderTarget(name).writtenThisFrame = true;\n }\n\n finishFrame(succeeded: boolean): void {\n for (const renderTarget of Object.values(this.renderTargets)) {\n if (succeeded && renderTarget.spec.lifetime === 'history' && renderTarget.writtenThisFrame) {\n const historyTexture = getHistoryTexture(renderTarget);\n const historyFramebuffer = getHistoryFramebuffer(renderTarget);\n renderTarget.historyTexture = renderTarget.texture;\n renderTarget.historyFramebuffer = renderTarget.framebuffer;\n renderTarget.texture = historyTexture;\n renderTarget.framebuffer = historyFramebuffer;\n renderTarget.historyInitialized = true;\n }\n renderTarget.writtenThisFrame = false;\n }\n }\n\n getRenderTarget(name: string): ManagedRenderTarget {\n const renderTarget = this.renderTargets[name];\n if (!renderTarget) {\n throw new Error(`${this.getOwnerName()}: unknown render target \"${name}\"`);\n }\n return renderTarget;\n }\n\n resolveBindings(options: {\n execution: EffectiveSubPass;\n originalTexture: Texture;\n previousTexture: Texture;\n outputTexture: Texture;\n externalBindings: Record<string, ShaderPassBinding>;\n }): Record<string, ShaderPassBinding> {\n const {execution, originalTexture, previousTexture, outputTexture, externalBindings} = options;\n const inputMap = execution.inputs || {sourceTexture: 'previous'};\n const shaderInputBindings = this.shaderInputs.getModuleBindingValues(execution.shaderPass.name);\n const externalBindingsForPass = Object.fromEntries(\n Object.entries(externalBindings).filter(([name]) =>\n execution.shaderPass.bindingLayout?.some(binding => binding.name === name)\n )\n );\n // Shader-pass bindings stored in `shaderInputs` act as renderer-owned defaults. Per-draw\n // external bindings can override those defaults for frame-specific resources, while routed\n // logical inputs such as `sourceTexture` remain authoritative below.\n const resolvedBindings: Record<string, ShaderPassBinding> = {\n ...shaderInputBindings,\n ...externalBindingsForPass\n };\n const outputName = execution.output || 'previous';\n\n for (const [bindingName, inputSource] of Object.entries(inputMap)) {\n if (!inputSource) {\n continue;\n }\n const texture = this.resolveInputTexture(inputSource, originalTexture, previousTexture);\n const target = inputSource in this.renderTargets ? this.renderTargets[inputSource] : null;\n if (\n outputName !== 'previous' &&\n inputSource === outputName &&\n target?.spec.lifetime !== 'history'\n ) {\n throw new Error(\n `${execution.ownerName}: subpass cannot read and write render target \"${outputName}\" in the same draw`\n );\n }\n if (bindingName === 'sourceTexture' && texture === outputTexture) {\n throw new Error(\n `${execution.ownerName}: subpass cannot sample from the render target it is writing to`\n );\n }\n resolvedBindings[bindingName] = texture;\n }\n\n if (!('sourceTexture' in resolvedBindings)) {\n resolvedBindings['sourceTexture'] = previousTexture;\n }\n\n return resolvedBindings;\n }\n\n private createStepExecutions(\n pipeline: ShaderPassPipeline,\n step: ShaderPassPipeline['steps'][number],\n flipY: boolean\n ): EffectiveSubPass[] {\n validateShaderPassDoesNotOwnRenderTargets(\n step.shaderPass,\n `${pipeline.name}/${step.shaderPass.name}`\n );\n\n return this.createPassExecutions(step.shaderPass, {\n ownerName: `${pipeline.name}/${step.shaderPass.name}`,\n firstInputs: step.inputs,\n lastOutput: step.output,\n uniformOverrides: step.uniforms,\n flipY\n });\n }\n\n private createPassExecutions(\n shaderPass: ShaderPass,\n options: {\n ownerName: string;\n firstInputs?: Partial<Record<string, ShaderPassInputSource<string>>>;\n lastOutput?: 'previous' | string;\n uniformOverrides?: Record<string, unknown>;\n flipY: boolean;\n }\n ): EffectiveSubPass[] {\n const subPasses = shaderPass.passes || [];\n return subPasses.map((subPass, index) => {\n const isFirstSubPass = index === 0;\n const isLastSubPass = index === subPasses.length - 1;\n const inputs =\n isFirstSubPass && options.firstInputs !== undefined ? options.firstInputs : subPass.inputs;\n const output =\n isLastSubPass && options.lastOutput !== undefined ? options.lastOutput : subPass.output;\n validateSubPassRouting(options.ownerName, inputs, output, this.renderTargets);\n\n return {\n ownerName: options.ownerName,\n shaderPass,\n subPassRenderer: new SubPassRenderer(this.device, shaderPass, subPass, options.flipY),\n inputs,\n output,\n uniforms: mergeUniforms(options.uniformOverrides, subPass.uniforms)\n };\n });\n }\n\n private resolveInputTexture(\n inputSource: string,\n originalTexture: Texture,\n previousTexture: Texture\n ): Texture {\n switch (inputSource) {\n case 'original':\n return originalTexture;\n case 'previous':\n return previousTexture;\n default: {\n const renderTarget = this.getRenderTarget(inputSource);\n if (renderTarget.spec.lifetime === 'history' && !renderTarget.writtenThisFrame) {\n return getHistoryTexture(renderTarget);\n }\n return renderTarget.texture;\n }\n }\n }\n\n private getOwnerName(): string {\n return this.passDefinition.name;\n }\n}\n\n/** Renders a single subpass of a `ShaderPass`. */\nclass SubPassRenderer {\n model: ClipSpace;\n shaderPass: ShaderPass;\n subPass: ShaderSubPass;\n flipY: boolean;\n\n constructor(device: Device, shaderPass: ShaderPass, subPass: ShaderSubPass, flipY: boolean) {\n this.shaderPass = shaderPass;\n this.subPass = subPass;\n this.flipY = flipY;\n const action =\n subPass.action || (subPass.filter && 'filter') || (subPass.sampler && 'sample') || 'filter';\n const fs = getFragmentShaderForRenderPass({\n shaderPass,\n action,\n shadingLanguage: device.info.shadingLanguage\n });\n\n this.model = new ClipSpace(device, {\n id: `${shaderPass.name}-subpass`,\n source: fs,\n fs,\n modules: [textureTransform, shaderPass],\n parameters: {\n depthWriteEnabled: false\n }\n });\n }\n\n destroy() {\n this.model.destroy();\n }\n\n prepare(options: {\n commandEncoder: CommandEncoder;\n bindings: Record<string, ShaderPassBinding>;\n textureScale: [number, number];\n uniforms?: Record<string, unknown>;\n }): void {\n const {commandEncoder, bindings, textureScale, uniforms} = options;\n\n this.model.shaderInputs.setProps({\n textureTransform: {scale: textureScale, flipY: this.flipY ? 1 : 0}\n });\n this.model.shaderInputs.setProps({\n [this.shaderPass.name]: this.shaderPass.uniforms || {}\n });\n this.model.shaderInputs.setProps({\n [this.shaderPass.name]: uniforms || {}\n });\n this.model.setBindings(bindings || {});\n this.model.predraw(commandEncoder);\n }\n\n draw(renderPass: RenderPass): void {\n this.model.draw(renderPass);\n }\n}\n\nfunction getExecutableShaderPasses(shaderPasses: ShaderPassLike[]): ShaderPass[] {\n return shaderPasses.flatMap(shaderPass =>\n isShaderPassPipeline(shaderPass) ? shaderPass.steps.map(step => step.shaderPass) : [shaderPass]\n );\n}\n\nfunction isShaderPassPipeline(shaderPass: ShaderPassLike): shaderPass is ShaderPassPipeline {\n return 'steps' in shaderPass;\n}\n\nfunction validateShaderPassDoesNotOwnRenderTargets(\n shaderPass: ShaderPass,\n ownerName: string\n): void {\n const renderTargets = (shaderPass as ShaderPass & {renderTargets?: Record<string, unknown>})\n .renderTargets;\n if (renderTargets && Object.keys(renderTargets).length > 0) {\n throw new Error(\n `${ownerName}: ShaderPass.renderTargets is not supported; use ShaderPassPipeline.renderTargets instead`\n );\n }\n}\n\nfunction validateRenderTargetNames(\n ownerName: string,\n renderTargets: Record<string, ShaderPassRenderTarget>\n): void {\n for (const name of Object.keys(renderTargets)) {\n if (RESERVED_RENDER_TARGET_NAMES.has(name)) {\n throw new Error(`${ownerName}: render target name \"${name}\" is reserved`);\n }\n }\n}\n\nfunction validateSubPassRouting(\n ownerName: string,\n inputs: Partial<Record<string, ShaderPassInputSource<string>>> | undefined,\n output: 'previous' | string | undefined,\n renderTargets: Record<string, ManagedRenderTarget>\n): void {\n const inputMap = inputs || {sourceTexture: 'previous'};\n for (const inputSource of Object.values(inputMap)) {\n if (\n inputSource &&\n inputSource !== 'original' &&\n inputSource !== 'previous' &&\n !(inputSource in renderTargets)\n ) {\n throw new Error(`${ownerName}: unknown input source \"${inputSource}\"`);\n }\n }\n\n if (output && output !== 'previous' && !(output in renderTargets)) {\n throw new Error(`${ownerName}: unknown output target \"${output}\"`);\n }\n}\n\nfunction mergeUniforms(\n baseUniforms?: Record<string, unknown>,\n subPassUniforms?: Record<string, unknown>\n): Record<string, unknown> | undefined {\n if (!baseUniforms && !subPassUniforms) {\n return undefined;\n }\n\n return {\n ...(baseUniforms || {}),\n ...(subPassUniforms || {})\n };\n}\n\n/**\n * Resolves the effective uniform block for one execution.\n *\n * Merge order is:\n * 1. persisted renderer-level shader inputs\n * 2. uniforms baked into the pipeline or subpass definition\n * 3. per-draw runtime overrides\n */\nfunction resolveExecutionUniforms(\n shaderInputs: ShaderInputs,\n execution: EffectiveSubPass,\n runtimeUniforms: Record<string, Record<string, unknown>>\n): Record<string, unknown> | undefined {\n return mergeUniforms(\n mergeUniforms(\n shaderInputs.getUniformValues()[execution.shaderPass.name] as Record<string, unknown>,\n execution.uniforms\n ),\n runtimeUniforms[execution.shaderPass.name]\n );\n}\n\nfunction createManagedRenderTargets(\n device: Device,\n renderTargets: Record<string, ShaderPassRenderTarget>\n): Record<string, ManagedRenderTarget> {\n const size = device.getCanvasContext().getDrawingBufferSize();\n return Object.entries(renderTargets).reduce(\n (managedRenderTargets, [name, spec]) => ({\n ...managedRenderTargets,\n [name]: createManagedRenderTarget(device, name, spec, size)\n }),\n {} as Record<string, ManagedRenderTarget>\n );\n}\n\nfunction destroyManagedRenderTargets(renderTargets: Record<string, ManagedRenderTarget>): void {\n for (const renderTarget of Object.values(renderTargets)) {\n renderTarget.framebuffer.destroy();\n renderTarget.texture.destroy();\n renderTarget.historyFramebuffer?.destroy();\n renderTarget.historyTexture?.destroy();\n }\n}\n\nfunction resizeManagedRenderTargets(\n device: Device,\n renderTargets: Record<string, ManagedRenderTarget>,\n size: [width: number, height: number]\n): void {\n for (const renderTarget of Object.values(renderTargets)) {\n const targetSize = getRenderTargetSize(size, renderTarget.spec.scale);\n if (\n renderTarget.texture.width === targetSize[0] &&\n renderTarget.texture.height === targetSize[1]\n ) {\n continue;\n }\n\n renderTarget.framebuffer.destroy();\n renderTarget.texture.destroy();\n renderTarget.historyFramebuffer?.destroy();\n renderTarget.historyTexture?.destroy();\n const replacement = createManagedRenderTarget(\n device,\n renderTarget.name,\n renderTarget.spec,\n size\n );\n renderTarget.texture = replacement.texture;\n renderTarget.framebuffer = replacement.framebuffer;\n renderTarget.historyTexture = replacement.historyTexture;\n renderTarget.historyFramebuffer = replacement.historyFramebuffer;\n renderTarget.historyInitialized = false;\n renderTarget.writtenThisFrame = false;\n }\n}\n\nfunction createManagedRenderTarget(\n device: Device,\n name: string,\n spec: ShaderPassRenderTarget,\n size: [number, number]\n): ManagedRenderTarget {\n const targetSize = getRenderTargetSize(size, spec.scale);\n const {texture, framebuffer} = createTargetResources(device, name, spec, targetSize);\n let historyTexture: Texture | undefined;\n let historyFramebuffer: Framebuffer | undefined;\n if (spec.lifetime === 'history') {\n const historyResources = createTargetResources(device, `${name}-history`, spec, targetSize);\n historyTexture = historyResources.texture;\n historyFramebuffer = historyResources.framebuffer;\n }\n\n return {\n name,\n spec,\n texture,\n framebuffer,\n historyTexture,\n historyFramebuffer,\n historyInitialized: false,\n writtenThisFrame: false\n };\n}\n\nfunction createTargetResources(\n device: Device,\n name: string,\n spec: ShaderPassRenderTarget,\n targetSize: [number, number]\n): {texture: Texture; framebuffer: Framebuffer} {\n const texture = device.createTexture({\n id: `${name}-texture`,\n width: targetSize[0],\n height: targetSize[1],\n format: spec.format || device.preferredColorFormat,\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_SRC | Texture.COPY_DST,\n ...(spec.sampler ? {sampler: spec.sampler} : {})\n });\n const framebuffer = device.createFramebuffer({\n id: `${name}-framebuffer`,\n width: targetSize[0],\n height: targetSize[1],\n colorAttachments: [texture]\n });\n\n return {texture, framebuffer};\n}\n\nfunction getHistoryTexture(renderTarget: ManagedRenderTarget): Texture {\n if (!renderTarget.historyTexture) {\n throw new Error(`${renderTarget.name}: transient render target has no history texture`);\n }\n return renderTarget.historyTexture;\n}\n\nfunction getHistoryFramebuffer(renderTarget: ManagedRenderTarget): Framebuffer {\n if (!renderTarget.historyFramebuffer) {\n throw new Error(`${renderTarget.name}: transient render target has no history framebuffer`);\n }\n return renderTarget.historyFramebuffer;\n}\n\nfunction getRenderTargetSize(\n size: [width: number, height: number],\n scale: [number, number] = [1, 1]\n): [width: number, height: number] {\n return [Math.max(1, Math.round(size[0] * scale[0])), Math.max(1, Math.round(size[1] * scale[1]))];\n}\n\nfunction getFramebufferTexture(framebuffer: Framebuffer): Texture {\n const texture = framebuffer.colorAttachments[0]?.texture;\n if (!texture) {\n throw new Error('ShaderPassRenderer: framebuffer is missing a color attachment texture');\n }\n return texture;\n}\n\nfunction getNextPreviousFramebuffer(\n swapFramebuffers: SwapFramebuffers,\n previousFramebuffer: Framebuffer | null\n): Framebuffer {\n if (previousFramebuffer === swapFramebuffers.current) {\n return swapFramebuffers.next;\n }\n return swapFramebuffers.current;\n}\n\nfunction getSeedFramebuffer(\n swapFramebuffers: SwapFramebuffers,\n originalTexture: Texture\n): Framebuffer {\n if (getFramebufferTexture(swapFramebuffers.current) === originalTexture) {\n return swapFramebuffers.next;\n }\n return swapFramebuffers.current;\n}\n\nfunction calculateTextureScale(\n sourceTexture: Texture,\n outputTexture: Texture\n): [scaleX: number, scaleY: number] {\n const sourceAspect = sourceTexture.width / sourceTexture.height;\n const outputAspect = outputTexture.width / outputTexture.height;\n\n if (outputAspect > sourceAspect) {\n return [1, outputAspect / sourceAspect];\n }\n\n return [sourceAspect / outputAspect, 1];\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {BufferProps, FramebufferProps} from '@luma.gl/core';\nimport {Device, Resource, Buffer, Framebuffer, Texture} from '@luma.gl/core';\n\n/**\n * Helper class for working with repeated transformations / computations\n * Primarily intended for GPU buffers `Swap<Buffer>` or textures `Swap<Texture>`)\n * @note the two resources are expected to be structurally identical (same size, length, format, etc)\n * @note the two resources can be destroyed by calling `destroy()`\n */\nexport class Swap<T extends Resource<any>> {\n id: string;\n\n /** The current resource - usually the source for renders or computations */\n current: T;\n /** The next resource - usually the target/destination for transforms / computations */\n next: T;\n\n constructor(props: {current: T; next: T; id?: string}) {\n this.id = props.id || 'swap';\n this.current = props.current;\n this.next = props.next;\n }\n\n /** Destroys the two managed resources */\n destroy() {\n this.current?.destroy();\n this.next?.destroy();\n }\n\n /** Make the next resource into the current resource, and reuse the current resource as the next resource */\n swap() {\n const current = this.current;\n this.current = this.next;\n this.next = current;\n }\n}\n\n/** Helper for managing double-buffered framebuffers */\nexport class SwapFramebuffers extends Swap<Framebuffer> {\n constructor(device: Device, props: FramebufferProps) {\n props = {...props};\n\n const {width = 1, height = 1} = props;\n\n let colorAttachments = props.colorAttachments?.map(colorAttachment =>\n typeof colorAttachment !== 'string'\n ? colorAttachment\n : device.createTexture({\n id: `${props.id}-texture-0`,\n format: colorAttachment,\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_SRC | Texture.COPY_DST,\n width,\n height\n })\n );\n\n const current = device.createFramebuffer({...props, colorAttachments});\n\n colorAttachments = props.colorAttachments?.map(colorAttachment =>\n typeof colorAttachment !== 'string'\n ? colorAttachment\n : device.createTexture({\n id: `${props.id}-texture-1`,\n format: colorAttachment,\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_SRC | Texture.COPY_DST,\n width,\n height\n })\n );\n\n const next = device.createFramebuffer({...props, colorAttachments});\n\n super({current, next});\n\n for (const [index, colorAttachment] of (props.colorAttachments || []).entries()) {\n if (typeof colorAttachment === 'string') {\n current.attachResource(current.colorAttachments[index].texture);\n next.attachResource(next.colorAttachments[index].texture);\n }\n }\n }\n\n /**\n * Resizes the Framebuffers.\n * @returns true if the size changed, otherwise exiting framebuffers were preserved\n * @note any contents are not preserved!\n */\n resize(size: {width: number; height: number}): boolean {\n if (size.width === this.current.width && size.height === this.current.height) {\n return false;\n }\n const {current, next} = this;\n\n this.current = current.clone(size);\n attachFramebufferAttachments(this.current);\n current.destroy();\n\n this.next = next.clone(size);\n attachFramebufferAttachments(this.next);\n next.destroy();\n\n return true;\n }\n}\n\n/** Framebuffer.clone() creates fresh attachments that the replacement framebuffer must own. */\nfunction attachFramebufferAttachments(framebuffer: Framebuffer): void {\n for (const colorAttachment of framebuffer.colorAttachments) {\n framebuffer.attachResource(colorAttachment.texture);\n }\n if (framebuffer.depthStencilAttachment) {\n framebuffer.attachResource(framebuffer.depthStencilAttachment.texture);\n }\n}\n\n/** Helper for managing double-buffered GPU buffers */\nexport class SwapBuffers extends Swap<Buffer> {\n constructor(device: Device, props: BufferProps) {\n super({current: device.createBuffer(props), next: device.createBuffer(props)});\n }\n\n /**\n * Resizes the Buffers.\n * @returns true if the size changed, otherwise exiting buffers were preserved.\n * @note any contents are not preserved!\n */\n resize(props: {byteLength: number}) {\n if (props.byteLength === this.current.byteLength) {\n return false;\n }\n\n const {current, next} = this;\n\n this.current = current.clone(props);\n current.destroy();\n\n this.next = next.clone(props);\n next.destroy();\n\n return true;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderPass} from '@luma.gl/shadertools';\n\n/**\n * Gets fragment shader source for a shader pass sub pass\n * @param options\n * @returns\n */\nexport function getFragmentShaderForRenderPass(options: {\n shaderPass: ShaderPass;\n action: 'filter' | 'sample';\n shadingLanguage: 'wgsl' | 'glsl';\n}): string {\n const {shaderPass, action, shadingLanguage} = options;\n switch (action) {\n case 'filter':\n const filterFunc = `${shaderPass.name}_filterColor_ext`;\n return shadingLanguage === 'wgsl'\n ? getFilterShaderWGSL(filterFunc)\n : getFilterShaderGLSL(filterFunc);\n\n case 'sample':\n const samplerFunc = `${shaderPass.name}_sampleColor`;\n return shadingLanguage === 'wgsl'\n ? getSamplerShaderWGSL(samplerFunc)\n : getSamplerShaderGLSL(samplerFunc);\n\n default:\n throw new Error(`${shaderPass.name} no fragment shader generated for shader pass`);\n }\n}\n\n/** Get a filtering WGSL fragment shader */\nfunction getFilterShaderWGSL(func: string) {\n return /* wgsl */ `\\\n@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;\n@group(0) @binding(auto) var sourceTextureSampler: sampler;\n\n@fragment\nfn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {\n let texCoord = shaderPassRenderer_getTextureUV(inputs.coordinate);\n let texSize = vec2f(textureDimensions(sourceTexture));\n\n var fragColor = textureSample(sourceTexture, sourceTextureSampler, texCoord);\n fragColor = ${func}(fragColor, texSize, texCoord);\n return fragColor;\n}\n`;\n}\n\n/** Get a sampling WGSL fragment shader */\nfunction getSamplerShaderWGSL(func: string) {\n return /* wgsl */ `\\\n@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;\n@group(0) @binding(auto) var sourceTextureSampler: sampler;\n\n@fragment\nfn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {\n let texCoord = shaderPassRenderer_getTextureUV(inputs.coordinate);\n let texSize = vec2f(textureDimensions(sourceTexture));\n return ${func}(sourceTexture, sourceTextureSampler, texSize, texCoord);\n}\n`;\n}\n\n/** Get a filtering GLSL fragment shader */\nfunction getFilterShaderGLSL(func: string) {\n return /* glsl */ `\\\n#version 300 es\n\nuniform sampler2D sourceTexture;\n\nin vec2 position;\nin vec2 coordinate;\nin vec2 uv;\n\nout vec4 fragColor;\n\nvoid main() {\n vec2 texCoord = shaderPassRenderer_getTextureUV(coordinate);\n ivec2 iTexSize = textureSize(sourceTexture, 0);\n vec2 texSize = vec2(float(iTexSize.x), float(iTexSize.y));\n\n fragColor = texture(sourceTexture, texCoord);\n fragColor = ${func}(fragColor, texSize, texCoord);\n}\n`;\n}\n\n/** Get a sampling GLSL fragment shader */\nfunction getSamplerShaderGLSL(func: string) {\n return /* glsl */ `\\\n#version 300 es\n\nuniform sampler2D sourceTexture;\n\nin vec2 position;\nin vec2 coordinate;\nin vec2 uv;\n\nout vec4 fragColor;\n\nvoid main() {\n vec2 texCoord = shaderPassRenderer_getTextureUV(coordinate);\n ivec2 iTexSize = textureSize(sourceTexture, 0);\n vec2 texSize = vec2(float(iTexSize.x), float(iTexSize.y));\n\n fragColor = ${func}(sourceTexture, texSize, texCoord);\n}\n`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nexport const textureTransform = {\n name: 'textureTransform',\n source: /* wgsl */ `\nstruct textureTransformUniforms {\n scale: vec2<f32>,\n flipY: i32,\n};\n@group(0) @binding(auto) var<uniform> textureTransform: textureTransformUniforms;\n\nfn shaderPassRenderer_getTextureUV(uv: vec2f) -> vec2f {\n var position = (uv - vec2f(0.5, 0.5)) / textureTransform.scale + vec2f(0.5, 0.5);\n if (textureTransform.flipY != 0) {\n position.y = 1.0 - position.y;\n }\n return position;\n}\n\nfn shaderPassRenderer_getRenderTargetUV(textureUV: vec2f) -> vec2f {\n let unscaledCoord = (textureUV - vec2f(0.5, 0.5)) * textureTransform.scale + vec2f(0.5, 0.5);\n return select(vec2f(unscaledCoord.x, 1.0 - unscaledCoord.y), unscaledCoord, textureTransform.flipY != 0);\n}\n`,\n fs: /* glsl */ `\nlayout(std140) uniform textureTransformUniforms {\n vec2 scale;\n int flipY;\n} textureTransform;\n\nvec2 shaderPassRenderer_getTextureUV(vec2 coord) {\n vec2 position = (coord - 0.5) / textureTransform.scale + 0.5;\n if (textureTransform.flipY != 0) {\n position.y = 1.0 - position.y;\n }\n return position;\n}\n\nvec2 shaderPassRenderer_getRenderTargetUV(vec2 textureUV) {\n vec2 unscaledCoord = (textureUV - 0.5) * textureTransform.scale + 0.5;\n return textureTransform.flipY != 0 ? unscaledCoord : vec2(unscaledCoord.x, 1.0 - unscaledCoord.y);\n}\n`,\n uniformTypes: {\n scale: 'vec2<f32>',\n flipY: 'i32'\n }\n} as const satisfies ShaderModule<{}, {scale: [number, number]; flipY: number}>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n type DeviceFeature,\n type ComputePipelineProps,\n type Shader,\n type Binding,\n type CommandEncoder,\n Device,\n Buffer,\n ComputePipeline,\n ComputePass,\n PipelineFactory,\n ShaderFactory,\n UniformStore,\n log,\n dataTypeDecoder\n} from '@luma.gl/core';\nimport {\n type ShaderModule,\n type ShaderPlugin,\n type PlatformInfo,\n mergeShaderPluginModules,\n resolveShaderPlugins,\n ShaderAssembler\n} from '@luma.gl/shadertools';\nimport {type TypedArray, isNumericArray} from '@math.gl/types';\nimport {ShaderInputs} from '../shader-inputs';\nimport {\n mergeShaderModules,\n mergeShaderModuleBindingsIntoLayout,\n shaderModuleHasUniforms\n} from '../utils/shader-module-utils';\nimport {uid} from '../utils/uid';\n// import {getDebugTableForShaderLayout} from '../debug/debug-shader-layout';\n\nconst LOG_DRAW_PRIORITY = 2;\nconst LOG_DRAW_TIMEOUT = 10000;\n\nexport type ComputationProps = Omit<ComputePipelineProps, 'shader'> & {\n source?: string;\n\n /** Shadertools shader modules added to shader code. */\n modules?: ShaderModule[];\n /** Shadertools boolean or numeric preprocessor defines that configure shader code. */\n defines?: Record<string, boolean | number>;\n /** Reusable shader assembly plugins resolved for WGSL compute assembly. */\n plugins?: ShaderPlugin[];\n\n /** Shader inputs, used to generate uniform buffers and bindings. */\n shaderInputs?: ShaderInputs;\n\n /** Bindings */\n bindings?: Record<string, Binding>;\n\n /** Show shader source in browser? */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n\n /** Factory used to create a {@link ComputePipeline}. Defaults to {@link Device} default factory. */\n pipelineFactory?: PipelineFactory;\n /** Factory used to create a {@link Shader}. Defaults to {@link Device} default factory. */\n shaderFactory?: ShaderFactory;\n /** Shader assembler. Defaults to the ShaderAssembler.getShaderAssembler() */\n shaderAssembler?: ShaderAssembler;\n};\n\n/**\n * v9 Model API\n * A model\n * - automatically reuses pipelines (programs) when possible\n * - automatically rebuilds pipelines if necessary to accommodate changed settings\n * shadertools integration\n * - accepts modules and performs shader transpilation\n */\nexport class Computation {\n static defaultProps: Required<ComputationProps> = {\n ...ComputePipeline.defaultProps,\n id: 'unnamed',\n handle: undefined,\n userData: {},\n\n source: '',\n modules: [],\n defines: {},\n plugins: [],\n\n bindings: undefined!,\n shaderInputs: undefined!,\n\n pipelineFactory: undefined!,\n shaderFactory: undefined!,\n shaderAssembler: ShaderAssembler.getDefaultShaderAssembler(),\n\n debugShaders: undefined!\n };\n\n readonly device: Device;\n readonly id: string;\n\n readonly pipelineFactory: PipelineFactory;\n readonly shaderFactory: ShaderFactory;\n\n userData: {[key: string]: any} = {};\n\n /** Bindings (textures, samplers, uniform buffers) */\n bindings: Record<string, Binding> = {};\n\n /** The underlying GPU pipeline. */\n pipeline: ComputePipeline;\n /** Assembled compute shader source */\n source: string;\n /** the underlying compiled compute shader */\n // @ts-ignore Set in function called from constructor\n shader: Shader;\n\n /** ShaderInputs instance */\n shaderInputs: ShaderInputs;\n\n // @ts-ignore Set in function called from constructor\n _uniformStore: UniformStore;\n\n _pipelineNeedsUpdate: string | false = 'newly created';\n\n private _getModuleUniforms: (props?: Record<string, Record<string, any>>) => Record<string, any>;\n private props: Required<ComputationProps>;\n\n private _destroyed = false;\n\n constructor(device: Device, props: ComputationProps) {\n if (device.type !== 'webgpu') {\n throw new Error('Computation is only supported in WebGPU');\n }\n\n this.props = {...Computation.defaultProps, ...props};\n props = this.props;\n this.id = props.id || uid('model');\n this.device = device;\n\n Object.assign(this.userData, props.userData);\n\n const platformInfo = getPlatformInfo(device);\n const resolvedPlugins = resolveShaderPlugins(this.props.plugins, platformInfo.shaderLanguage);\n if (\n Object.keys(resolvedPlugins.vertexInputs).length > 0 ||\n Object.keys(resolvedPlugins.varyings).length > 0\n ) {\n throw new Error('Computation does not support ShaderPlugin vertex inputs or varyings');\n }\n\n // Setup shader module inputs\n const shaderInputModules = mergeShaderPluginModules(\n this.props.modules,\n resolvedPlugins.modules\n );\n const moduleMap = Object.fromEntries(shaderInputModules.map(module => [module.name, module]));\n // @ts-ignore TODO - fix up typing?\n this.shaderInputs = props.shaderInputs || new ShaderInputs(moduleMap);\n if (props.shaderInputs && resolvedPlugins.modules.length > 0) {\n this.shaderInputs.addModules(resolvedPlugins.modules);\n }\n this.setShaderInputs(this.shaderInputs);\n\n // Setup shader assembler\n const modules = mergeShaderModules(this.props.modules, this.shaderInputs?.getModules());\n const defines = {...resolvedPlugins.defines, ...this.props.defines};\n\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(this.props.shaderLayout, modules) || null;\n\n this.pipelineFactory =\n props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);\n this.shaderFactory = props.shaderFactory || ShaderFactory.getDefaultShaderFactory(this.device);\n\n const {source, getUniforms} = this.props.shaderAssembler.assembleWGSLShader({\n platformInfo,\n ...this.props,\n modules,\n defines,\n pluginInjections: resolvedPlugins.injections\n });\n\n this.source = source;\n // @ts-ignore\n this._getModuleUniforms = getUniforms;\n const inferredShaderLayout = (\n device as Device & {getShaderLayout?: (source: string) => any}\n ).getShaderLayout?.(this.source);\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(\n this.props.shaderLayout || inferredShaderLayout || null,\n modules\n ) || null;\n\n // Create the pipeline\n // @note order is important\n this.pipeline = this._updatePipeline();\n\n // Apply any dynamic settings that will not trigger pipeline change\n if (props.bindings) {\n this.setBindings(props.bindings);\n }\n }\n\n destroy(): void {\n if (this._destroyed) return;\n this.pipelineFactory.release(this.pipeline);\n this.shaderFactory.release(this.shader);\n this._uniformStore.destroy();\n this._destroyed = true;\n }\n\n // Draw call\n\n /**\n * Updates compute shader inputs before opening the compute pass that will\n * consume them.\n */\n predraw(commandEncoder: CommandEncoder) {\n // Update uniform buffers if needed\n this.updateShaderInputs(commandEncoder);\n }\n\n dispatch(computePass: ComputePass, x: number, y?: number, z?: number): void {\n try {\n this._logDrawCallStart();\n\n // Check if the pipeline is invalidated\n // TODO - this is likely the worst place to do this from performance perspective. Perhaps add a predraw()?\n this.pipeline = this._updatePipeline();\n\n // Set pipeline state, we may be sharing a pipeline so we need to set all state on every draw\n // Any caching needs to be done inside the pipeline functions\n this.pipeline.setBindings(this.bindings);\n computePass.setPipeline(this.pipeline);\n // @ts-expect-error\n computePass.setBindings({});\n\n computePass.dispatch(x, y, z);\n } finally {\n this._logDrawCallEnd();\n }\n }\n\n // Update fixed fields (can trigger pipeline rebuild)\n\n // Update dynamic fields\n\n /**\n * Updates the vertex count (used in draw calls)\n * @note Any attributes with stepMode=vertex need to be at least this big\n */\n setVertexCount(vertexCount: number): void {\n // this.vertexCount = vertexCount;\n }\n\n /**\n * Updates the instance count (used in draw calls)\n * @note Any attributes with stepMode=instance need to be at least this big\n */\n setInstanceCount(instanceCount: number): void {\n // this.instanceCount = instanceCount;\n }\n\n setShaderInputs(shaderInputs: ShaderInputs): void {\n this.shaderInputs = shaderInputs;\n this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules);\n // Create uniform buffer bindings for all modules\n for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) {\n if (shaderModuleHasUniforms(module)) {\n const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName);\n this.bindings[`${moduleName}Uniforms`] = uniformBuffer;\n }\n }\n }\n\n /**\n * Updates shader module settings (which results in uniforms being set)\n */\n setShaderModuleProps(props: Record<string, any>): void {\n const uniforms = this._getModuleUniforms(props);\n\n // Extract textures & framebuffers set by the modules\n // TODO better way to extract bindings\n const keys = Object.keys(uniforms).filter(k => {\n const uniform = uniforms[k];\n return (\n !isNumericArray(uniform) && typeof uniform !== 'number' && typeof uniform !== 'boolean'\n );\n });\n const bindings: Record<string, Binding> = {};\n for (const k of keys) {\n bindings[k] = uniforms[k];\n delete uniforms[k];\n }\n }\n\n /**\n * Flushes current shader-input values into the internal uniform store.\n *\n * @param commandEncoder - Optional encoder used to order uniform uploads with\n * subsequent compute commands.\n */\n updateShaderInputs(commandEncoder?: CommandEncoder): void {\n this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(), commandEncoder);\n }\n\n /**\n * Sets bindings (textures, samplers, uniform buffers)\n */\n setBindings(bindings: Record<string, Binding>): void {\n Object.assign(this.bindings, bindings);\n }\n\n _setPipelineNeedsUpdate(reason: string): void {\n this._pipelineNeedsUpdate = this._pipelineNeedsUpdate || reason;\n }\n\n _updatePipeline(): ComputePipeline {\n if (this._pipelineNeedsUpdate) {\n let prevShader: Shader | null = null;\n if (this.pipeline) {\n log.log(\n 1,\n `Model ${this.id}: Recreating pipeline because \"${this._pipelineNeedsUpdate}\".`\n )();\n prevShader = this.shader;\n }\n\n this._pipelineNeedsUpdate = false;\n\n this.shader = this.shaderFactory.createShader({\n id: `${this.id}-fragment`,\n stage: 'compute',\n source: this.source,\n debugShaders: this.props.debugShaders\n });\n\n this.pipeline = this.pipelineFactory.createComputePipeline({\n ...this.props,\n shader: this.shader\n });\n\n if (prevShader) {\n this.shaderFactory.release(prevShader);\n }\n }\n return this.pipeline;\n }\n\n /** Throttle draw call logging */\n _lastLogTime = 0;\n _logOpen = false;\n\n _logDrawCallStart(): void {\n // IF level is 4 or higher, log every frame.\n const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;\n if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {\n return;\n }\n\n this._lastLogTime = Date.now();\n this._logOpen = true;\n\n log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {collapsed: log.level <= 2})();\n }\n\n _logDrawCallEnd(): void {\n if (this._logOpen) {\n // const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.props.shaderLayout, this.id);\n\n // log.table(logLevel, attributeTable)();\n // log.table(logLevel, uniformTable)();\n // log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();\n\n const uniformTable = this.shaderInputs.getDebugTable();\n log.table(LOG_DRAW_PRIORITY, uniformTable)();\n\n log.groupEnd(LOG_DRAW_PRIORITY)();\n this._logOpen = false;\n }\n }\n\n protected _drawCount = 0;\n\n // TODO - fix typing of luma data types\n _getBufferOrConstantValues(attribute: Buffer | TypedArray, dataType: any): string {\n const TypedArrayConstructor = dataTypeDecoder.getTypedArrayConstructor(dataType);\n const typedArray =\n attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;\n return typedArray.toString();\n }\n}\n\n/** Create a shadertools platform info from the Device */\nexport function getPlatformInfo(device: Device): PlatformInfo {\n return {\n type: device.type,\n shaderLanguage: device.info.shadingLanguage,\n shaderLanguageVersion: device.info.shadingLanguageVersion as 100 | 300,\n gpu: device.info.gpu,\n limits: device.limits as unknown as Record<string, number | undefined>,\n // HACK - we pretend that the DeviceFeatures is a Set, it has a similar API\n features: device.features as unknown as Set<DeviceFeature>\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Buffer, Device, Framebuffer, Texture} from '@luma.gl/core';\nimport {ShaderInputs} from '../../shader-inputs';\nimport {pickingUniforms, INVALID_INDEX} from './picking-uniforms';\n\nconst INDEX_PICKING_ATTACHMENT_INDEX = 1;\nconst INDEX_PICKING_CLEAR_COLOR = new Int32Array([INVALID_INDEX, INVALID_INDEX, 0, 0]);\nconst COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst COLOR_PICKING_MAX_BATCH_INDEX = 254;\nconst TOOLTIP_OFFSET_PIXELS = 14;\nconst TOOLTIP_MARGIN_PIXELS = 8;\n\n/** Information about picked object */\nexport type PickInfo = {\n batchIndex: number | null;\n objectIndex: number | null;\n};\n\n/** Text shown by `PickingManager` beside the latest picked cursor position. */\nexport type PickingTooltip = string | null;\n\nexport type PickingMode = 'auto' | 'index' | 'color';\nexport type ResolvedPickingMode = Exclude<PickingMode, 'auto'>;\nexport type PickingShouldPickOptions = {\n /** Re-render picking even when the cursor has not moved. */\n force?: boolean;\n};\n/** @deprecated Use `PickingMode`. */\nexport type PickingBackend = PickingMode;\n/** @deprecated Use `ResolvedPickingMode`. */\nexport type ResolvedPickingBackend = ResolvedPickingMode;\n\nexport type PickingManagerProps = {\n /** Shader inputs from models to pick */\n shaderInputs?: ShaderInputs<{picking: typeof pickingUniforms.props}>;\n /** Callback */\n onObjectPicked?: (info: PickInfo) => void;\n /**\n * Returns tooltip text for the latest pick result.\n * Returning `null` hides the tooltip.\n */\n getTooltip?: (info: PickInfo) => PickingTooltip;\n /** Select a picking mode. Defaults to `color`. Use `auto` to prefer `index` when supported. */\n mode?: PickingMode;\n /** @deprecated Use `mode`. */\n backend?: PickingBackend;\n};\n\nexport function resolvePickingMode(\n deviceType: Device['type'],\n mode: PickingMode = 'color',\n indexPickingSupported: boolean = deviceType === 'webgpu'\n): ResolvedPickingMode {\n if (mode === 'auto') {\n return indexPickingSupported ? 'index' : 'color';\n }\n\n if (mode === 'index' && !indexPickingSupported) {\n throw new Error(\n `Picking mode \"${mode}\" requires WebGPU or a WebGL device that supports renderable rg32sint textures.`\n );\n }\n\n return mode;\n}\n\nexport function supportsIndexPicking(device: Device): boolean {\n return (\n device.type === 'webgpu' ||\n (device.type === 'webgl' && device.isTextureFormatRenderable('rg32sint'))\n );\n}\n\n/** @deprecated Use `resolvePickingMode`. */\nexport const resolvePickingBackend = resolvePickingMode;\n\nexport function decodeIndexPickInfo(pixelData: Int32Array): PickInfo {\n return {\n objectIndex: pixelData[0] === INVALID_INDEX ? null : pixelData[0],\n batchIndex: pixelData[1] === INVALID_INDEX ? null : pixelData[1]\n };\n}\n\nexport function decodeColorPickInfo(pixelData: Uint8Array): PickInfo {\n const encodedObjectIndex = pixelData[0] + pixelData[1] * 256 + pixelData[2] * 65536;\n if (encodedObjectIndex === 0) {\n return {objectIndex: null, batchIndex: null};\n }\n\n const batchIndex = pixelData[3] > 0 ? pixelData[3] - 1 : 0;\n return {\n objectIndex: encodedObjectIndex - 1,\n batchIndex\n };\n}\n\n/**\n * Helper class for using object picking with backend-specific readback.\n * @todo Support multiple models\n * @todo Switching picking module\n */\nexport class PickingManager {\n device: Device;\n props: Required<PickingManagerProps>;\n mode: ResolvedPickingMode;\n /** Info from latest pick operation */\n pickInfo: PickInfo = {batchIndex: null, objectIndex: null};\n /** Framebuffer used for picking */\n framebuffer: Framebuffer | null = null;\n /** Last cursor position that triggered a picking render/readback. */\n protected lastMousePosition: [number, number] | null = null;\n /** Tooltip element created lazily when `getTooltip` returns visible content. */\n protected tooltipElement: HTMLDivElement | null = null;\n\n static defaultProps: Required<PickingManagerProps> = {\n shaderInputs: undefined!,\n onObjectPicked: () => {},\n getTooltip: () => null,\n mode: 'color',\n backend: 'color'\n };\n\n constructor(device: Device, props: PickingManagerProps) {\n this.device = device;\n this.props = {...PickingManager.defaultProps, ...props};\n const requestedMode = props.mode ?? props.backend ?? PickingManager.defaultProps.mode;\n this.props.mode = requestedMode;\n this.props.backend = requestedMode;\n this.mode = resolvePickingMode(\n this.device.type,\n requestedMode,\n supportsIndexPicking(this.device)\n );\n }\n\n destroy() {\n this.framebuffer?.destroy();\n this.tooltipElement?.remove();\n this.tooltipElement = null;\n }\n\n // TODO - Ask for a cached framebuffer? a Framebuffer factory?\n getFramebuffer() {\n if (!this.framebuffer) {\n this.framebuffer =\n this.mode === 'index' ? this.createIndexFramebuffer() : this.createColorFramebuffer();\n }\n return this.framebuffer;\n }\n\n /** Clear highlighted / picked object */\n clearPickState() {\n this.lastMousePosition = null;\n this.setPickingProps({highlightedBatchIndex: null, highlightedObjectIndex: null});\n this.hideTooltip();\n }\n\n /** Return whether callers need to render a fresh picking pass for this cursor position. */\n shouldPick(\n mousePosition: [number, number] | null | undefined,\n options: PickingShouldPickOptions = {}\n ): mousePosition is [number, number] {\n if (!mousePosition) {\n if (this.lastMousePosition) {\n this.clearPickState();\n }\n return false;\n }\n\n const [mouseX, mouseY] = mousePosition;\n if (\n !options.force &&\n this.lastMousePosition &&\n this.lastMousePosition[0] === mouseX &&\n this.lastMousePosition[1] === mouseY\n ) {\n return false;\n }\n\n this.lastMousePosition = [mouseX, mouseY];\n return true;\n }\n\n /** Prepare for rendering picking colors */\n beginRenderPass() {\n const framebuffer = this.getFramebuffer();\n framebuffer.resize(this.device.getDefaultCanvasContext().getDevicePixelSize());\n\n this.setPickingProps({isActive: true});\n\n return this.mode === 'index'\n ? this.device.beginRenderPass({\n framebuffer,\n clearColors: [new Float32Array([0, 0, 0, 0]), INDEX_PICKING_CLEAR_COLOR],\n clearDepth: 1\n })\n : this.device.beginRenderPass({\n framebuffer,\n clearColor: [0, 0, 0, 0],\n clearDepth: 1\n });\n }\n\n async updatePickInfo(mousePosition: [number, number]): Promise<PickInfo | null> {\n const framebuffer = this.getFramebuffer();\n const pickPosition = this.getPickPosition(mousePosition);\n const pickInfo = await this.readPickInfo(framebuffer, pickPosition);\n if (!pickInfo) {\n return null;\n }\n\n if (this.hasPickInfoChanged(pickInfo)) {\n this.pickInfo = pickInfo;\n this.props.onObjectPicked(pickInfo);\n }\n\n this.updateTooltip(pickInfo, mousePosition);\n this.setPickingProps({\n isActive: false,\n highlightedBatchIndex: pickInfo.batchIndex,\n highlightedObjectIndex: pickInfo.objectIndex\n });\n\n return this.pickInfo;\n }\n\n /**\n * Get pick position in device pixel range\n * use the center pixel location in device pixel range\n */\n getPickPosition(mousePosition: [number, number]): [number, number] {\n const yInvert = this.device.type !== 'webgpu';\n const devicePixels = this.device\n .getDefaultCanvasContext()\n .cssToDevicePixels(mousePosition, yInvert);\n const pickX = devicePixels.x + Math.floor(devicePixels.width / 2);\n const pickY = devicePixels.y + Math.floor(devicePixels.height / 2);\n return [pickX, pickY];\n }\n\n protected createIndexFramebuffer(): Framebuffer {\n const colorTexture = this.device.createTexture({\n format: 'rgba8unorm',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT\n });\n const pickingTexture = this.device.createTexture({\n format: 'rg32sint',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC\n });\n\n return this.device.createFramebuffer({\n colorAttachments: [colorTexture, pickingTexture],\n depthStencilAttachment: 'depth24plus'\n });\n }\n\n protected createColorFramebuffer(): Framebuffer {\n const pickingTexture = this.device.createTexture({\n format: 'rgba8unorm',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC\n });\n\n return this.device.createFramebuffer({\n colorAttachments: [pickingTexture],\n depthStencilAttachment: 'depth24plus'\n });\n }\n\n protected setPickingProps(props: Partial<typeof pickingUniforms.props>): void {\n this.props.shaderInputs?.setProps({picking: props});\n }\n\n protected async readPickInfo(\n framebuffer: Framebuffer,\n pickPosition: [number, number]\n ): Promise<PickInfo | null> {\n return this.mode === 'index'\n ? this.readIndexPickInfo(framebuffer, pickPosition)\n : this.readColorPickInfo(framebuffer, pickPosition);\n }\n\n protected async readIndexPickInfo(\n framebuffer: Framebuffer,\n [pickX, pickY]: [number, number]\n ): Promise<PickInfo | null> {\n if (this.device.type === 'webgpu') {\n const pickTexture = framebuffer.colorAttachments[INDEX_PICKING_ATTACHMENT_INDEX]?.texture;\n if (!pickTexture) {\n return null;\n }\n\n const layout = pickTexture.computeMemoryLayout({width: 1, height: 1});\n const readBuffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n try {\n pickTexture.readBuffer(\n {\n x: pickX,\n y: pickY,\n width: 1,\n height: 1\n },\n readBuffer\n );\n const pickDataView = await readBuffer.readAsync(0, layout.byteLength);\n return decodeIndexPickInfo(new Int32Array(pickDataView.buffer, pickDataView.byteOffset, 2));\n } finally {\n readBuffer.destroy();\n }\n }\n\n const pixelData = this.device.readPixelsToArrayWebGL(framebuffer, {\n sourceX: pickX,\n sourceY: pickY,\n sourceWidth: 1,\n sourceHeight: 1,\n sourceAttachment: INDEX_PICKING_ATTACHMENT_INDEX\n });\n\n return pixelData\n ? decodeIndexPickInfo(new Int32Array(pixelData.buffer, pixelData.byteOffset, 2))\n : null;\n }\n\n protected async readColorPickInfo(\n framebuffer: Framebuffer,\n [pickX, pickY]: [number, number]\n ): Promise<PickInfo | null> {\n if (this.device.type === 'webgpu') {\n const pickTexture = framebuffer.colorAttachments[0]?.texture;\n if (!pickTexture) {\n return null;\n }\n\n const layout = pickTexture.computeMemoryLayout({width: 1, height: 1});\n const readBuffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n try {\n pickTexture.readBuffer(\n {\n x: pickX,\n y: pickY,\n width: 1,\n height: 1\n },\n readBuffer\n );\n const pickDataView = await readBuffer.readAsync(0, layout.byteLength);\n return decodeColorPickInfo(new Uint8Array(pickDataView.buffer, pickDataView.byteOffset, 4));\n } finally {\n readBuffer.destroy();\n }\n }\n\n const pixelData = this.device.readPixelsToArrayWebGL(framebuffer, {\n sourceX: pickX,\n sourceY: pickY,\n sourceWidth: 1,\n sourceHeight: 1,\n sourceAttachment: 0\n });\n\n return pixelData\n ? decodeColorPickInfo(new Uint8Array(pixelData.buffer, pixelData.byteOffset, 4))\n : null;\n }\n\n protected hasPickInfoChanged(pickInfo: PickInfo): boolean {\n return (\n pickInfo.objectIndex !== this.pickInfo.objectIndex ||\n pickInfo.batchIndex !== this.pickInfo.batchIndex\n );\n }\n\n protected updateTooltip(pickInfo: PickInfo, mousePosition: [number, number]): void {\n const tooltipText = this.props.getTooltip(pickInfo);\n if (!tooltipText) {\n this.hideTooltip();\n return;\n }\n\n const tooltipElement = this.getOrCreateTooltipElement();\n if (!tooltipElement) {\n return;\n }\n\n tooltipElement.textContent = tooltipText;\n tooltipElement.style.display = 'block';\n this.positionTooltip(tooltipElement, mousePosition);\n }\n\n protected hideTooltip(): void {\n if (this.tooltipElement) {\n this.tooltipElement.style.display = 'none';\n }\n }\n\n protected getOrCreateTooltipElement(): HTMLDivElement | null {\n if (this.tooltipElement) {\n return this.tooltipElement;\n }\n if (\n typeof document === 'undefined' ||\n typeof window === 'undefined' ||\n typeof HTMLCanvasElement === 'undefined' ||\n typeof this.device.getDefaultCanvasContext !== 'function'\n ) {\n return null;\n }\n\n const canvas = this.device.getDefaultCanvasContext().canvas;\n if (!(canvas instanceof HTMLCanvasElement) || !canvas.parentElement) {\n return null;\n }\n\n const tooltipElement = document.createElement('div');\n tooltipElement.style.position = 'absolute';\n tooltipElement.style.zIndex = '12';\n tooltipElement.style.display = 'none';\n tooltipElement.style.maxWidth = '220px';\n tooltipElement.style.padding = '8px 10px';\n tooltipElement.style.borderRadius = '6px';\n tooltipElement.style.background = 'rgba(15, 23, 42, 0.92)';\n tooltipElement.style.color = '#f8fafc';\n tooltipElement.style.font = '600 13px/1.35 system-ui, sans-serif';\n tooltipElement.style.pointerEvents = 'none';\n tooltipElement.style.whiteSpace = 'nowrap';\n tooltipElement.style.boxShadow = '0 10px 24px rgba(15, 23, 42, 0.22)';\n\n const tooltipParent = canvas.parentElement;\n if (window.getComputedStyle(tooltipParent).position === 'static') {\n tooltipParent.style.position = 'relative';\n }\n tooltipParent.appendChild(tooltipElement);\n this.tooltipElement = tooltipElement;\n return tooltipElement;\n }\n\n protected positionTooltip(tooltipElement: HTMLDivElement, mousePosition: [number, number]): void {\n if (\n typeof HTMLCanvasElement === 'undefined' ||\n typeof this.device.getDefaultCanvasContext !== 'function'\n ) {\n return;\n }\n\n const canvas = this.device.getDefaultCanvasContext().canvas;\n if (!(canvas instanceof HTMLCanvasElement)) {\n return;\n }\n\n const maxLeft = Math.max(\n TOOLTIP_MARGIN_PIXELS,\n canvas.clientWidth - tooltipElement.offsetWidth - TOOLTIP_MARGIN_PIXELS\n );\n const maxTop = Math.max(\n TOOLTIP_MARGIN_PIXELS,\n canvas.clientHeight - tooltipElement.offsetHeight - TOOLTIP_MARGIN_PIXELS\n );\n const left = Math.min(mousePosition[0] + TOOLTIP_OFFSET_PIXELS, maxLeft);\n const top = Math.min(mousePosition[1] + TOOLTIP_OFFSET_PIXELS, maxTop);\n tooltipElement.style.left = `${Math.max(TOOLTIP_MARGIN_PIXELS, left)}px`;\n tooltipElement.style.top = `${Math.max(TOOLTIP_MARGIN_PIXELS, top)}px`;\n }\n}\n\nexport {COLOR_PICKING_MAX_BATCH_INDEX, COLOR_PICKING_MAX_OBJECT_INDEX};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumberArray4} from '@math.gl/types';\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\n/** Default color for auto highlight, a cyan color */\nconst DEFAULT_HIGHLIGHT_COLOR: NumberArray4 = [0, 1, 1, 1];\n\nexport const INVALID_INDEX = -1;\nexport type PickingPayloadMode = 'instance' | 'attribute' | 'vertex';\n\n/**\n * Props for the picking module, which depending on mode renders picking colors or highlighted item.\n * When active, renders picking colors, assumed to be rendered to off-screen \"picking\" buffer.\n * When inactive, renders normal colors, with the exception of selected object which is rendered with highlight\n * can distinguish between 2^32 different objects in each of 2^32 different batches.\n */\nexport type PickingProps = {\n /** Are we picking? I.e. rendering picking colors? */\n isActive?: boolean;\n /** Whether the payload is sourced from a builtin index or a custom integer attribute */\n indexMode?: PickingPayloadMode;\n /** Identifier of the batch currently being rendered */\n batchIndex?: number;\n\n /** Identifier of the highlighted batch */\n highlightedBatchIndex?: number | null;\n /** Set the highlighted object index, or `null` to explicitly clear **/\n highlightedObjectIndex?: number | null;\n /** Color of visual highlight of \"selected\" item () */\n highlightColor?: NumberArray4;\n};\n\n/**\n * Uniforms for the picking module, which renders picking colors and highlighted item.\n * When active, renders picking colors, assumed to be rendered to off-screen \"picking\" buffer.\n * When inactive, renders normal colors, with the exception of selected object which is rendered with highlight\n */\nexport type PickingUniforms = {\n /**\n * When true, renders picking colors. Set when rendering to off-screen \"picking\" buffer.\n * When false, renders normal colors, with the exception of selected object which is rendered with highlight\n */\n isActive: boolean;\n /** Whether the current payload comes from a builtin index or a custom integer attribute */\n indexMode: 0 | 1 | 2;\n /** Identifier of the batch currently being rendered */\n batchIndex: number;\n\n /** Do we have a highlighted item? */\n isHighlightActive: boolean;\n /** Color of visual highlight of \"selected\" item. Note: RGBA components must in the range 0-1 */\n highlightColor: NumberArray4;\n /** Indicates which batch to visually highlight an item in */\n highlightedBatchIndex: number;\n /** Indicates which object index in the batch to highlight */\n highlightedObjectIndex: number;\n};\n\nexport type PickingBindings = {};\n\n// GLSL_UNIFORMS\n\nconst uniformTypes: Required<ShaderModule<PickingProps, PickingUniforms>>['uniformTypes'] = {\n isActive: 'i32',\n indexMode: 'i32',\n batchIndex: 'i32',\n\n isHighlightActive: 'i32',\n highlightedBatchIndex: 'i32',\n highlightedObjectIndex: 'i32',\n highlightColor: 'vec4<f32>'\n};\n\nexport const GLSL_UNIFORMS = /* glsl */ `\\\nprecision highp float;\nprecision highp int;\n\nlayout(std140) uniform pickingUniforms {\n int isActive;\n int indexMode;\n int batchIndex;\n\n int isHighlightActive;\n int highlightedBatchIndex;\n int highlightedObjectIndex;\n vec4 highlightColor;\n} picking;\n`;\n\nexport const WGSL_UNIFORMS = /* wgsl */ `\\\nstruct pickingUniforms {\n isActive: i32,\n indexMode: i32,\n batchIndex: i32,\n\n isHighlightActive: i32,\n highlightedBatchIndex: i32,\n highlightedObjectIndex: i32,\n highlightColor: vec4<f32>,\n};\n\n@group(0) @binding(auto) var<uniform> picking: pickingUniforms;\n`;\n\nfunction getUniforms(props: PickingProps = {}, prevUniforms?: PickingUniforms): PickingUniforms {\n const uniforms = {...prevUniforms} as PickingUniforms;\n\n // picking\n if (props.isActive !== undefined) {\n uniforms.isActive = Boolean(props.isActive);\n }\n\n switch (props.indexMode) {\n case 'instance':\n uniforms.indexMode = 0;\n break;\n case 'attribute':\n uniforms.indexMode = 1;\n break;\n case 'vertex':\n uniforms.indexMode = 2;\n break;\n case undefined:\n // no change\n break;\n }\n\n if (typeof props.batchIndex === 'number') {\n uniforms.batchIndex = props.batchIndex;\n }\n\n switch (props.highlightedObjectIndex) {\n case undefined:\n // Unless highlighted payload explicitly null or set, do not update state\n break;\n case null:\n // Clear highlight\n uniforms.isHighlightActive = false;\n uniforms.highlightedObjectIndex = INVALID_INDEX;\n break;\n default:\n uniforms.isHighlightActive = true;\n uniforms.highlightedObjectIndex = props.highlightedObjectIndex;\n }\n\n switch (props.highlightedBatchIndex) {\n case undefined:\n break;\n case null:\n uniforms.isHighlightActive = false;\n uniforms.highlightedBatchIndex = INVALID_INDEX;\n break;\n default:\n uniforms.isHighlightActive = true;\n uniforms.highlightedBatchIndex = props.highlightedBatchIndex;\n }\n\n if (props.highlightColor) {\n uniforms.highlightColor = props.highlightColor;\n }\n\n return uniforms;\n}\n\n/**\n * Provides support for color-based picking and highlighting.\n *\n * In particular, supports picking a specific instance in an instanced\n * draw call and highlighting an instance based on its picking color,\n * and correspondingly, supports picking and highlighting groups of\n * primitives with the same picking color in non-instanced draw-calls\n *\n * @note Color based picking has the significant advantage in that it can be added to any\n * existing shader without requiring any additional picking logic.\n */\nexport const pickingUniforms = {\n props: {} as PickingProps,\n uniforms: {} as PickingUniforms,\n\n name: 'picking',\n\n uniformTypes,\n defaultUniforms: {\n isActive: false,\n indexMode: 0,\n batchIndex: 0,\n isHighlightActive: false,\n highlightedBatchIndex: INVALID_INDEX,\n highlightedObjectIndex: INVALID_INDEX,\n highlightColor: DEFAULT_HIGHLIGHT_COLOR\n },\n\n getUniforms\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nimport type {PickingBindings, PickingProps, PickingUniforms} from './picking-uniforms';\nimport {pickingUniforms, GLSL_UNIFORMS, WGSL_UNIFORMS, INVALID_INDEX} from './picking-uniforms';\n\nconst source = /* wgsl */ `\\\n${WGSL_UNIFORMS}\n\nconst COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\nconst COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst COLOR_PICKING_MAX_BATCH_INDEX = 254;\n\nfn picking_setObjectIndex(objectIndex: i32) -> i32 {\n return objectIndex;\n}\n\nfn picking_isObjectHighlighted(objectIndex: i32) -> bool {\n return\n picking.isHighlightActive != 0 &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == objectIndex;\n}\n\nfn picking_filterHighlightColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0 || !picking_isObjectHighlighted(objectIndex)) {\n return color;\n }\n\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n if (blendedAlpha == 0.0) {\n return vec4<f32>(color.rgb, 0.0);\n }\n\n let highLightRatio = highLightAlpha / blendedAlpha;\n let blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4<f32>(blendedRGB, blendedAlpha);\n}\n\nfn picking_canEncodePickInfo(objectIndex: i32) -> bool {\n return\n objectIndex != COLOR_PICKING_INVALID_INDEX &&\n objectIndex >= 0 &&\n objectIndex <= COLOR_PICKING_MAX_OBJECT_INDEX &&\n picking.batchIndex >= 0 &&\n picking.batchIndex <= COLOR_PICKING_MAX_BATCH_INDEX;\n}\n\nfn picking_getPickingColor(objectIndex: i32) -> vec4<f32> {\n if (!picking_canEncodePickInfo(objectIndex)) {\n return vec4<f32>(0.0, 0.0, 0.0, 0.0);\n }\n\n let encodedObjectIndex = objectIndex + 1;\n let red = encodedObjectIndex % 256;\n let green = (encodedObjectIndex / 256) % 256;\n let blue = (encodedObjectIndex / 65536) % 256;\n let alpha = picking.batchIndex + 1;\n\n return vec4<f32>(\n f32(red) / 255.0,\n f32(green) / 255.0,\n f32(blue) / 255.0,\n f32(alpha) / 255.0\n );\n}\n\nfn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0) {\n if (!picking_canEncodePickInfo(objectIndex)) {\n discard;\n }\n return picking_getPickingColor(objectIndex);\n }\n\n return color;\n}\n`;\n\nconst vs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int INDEX_PICKING_MODE_INSTANCE = 0;\nconst int INDEX_PICKING_MODE_CUSTOM = 1;\n\nconst int COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\n\nflat out int picking_objectIndex;\n\nvoid picking_setObjectIndex(int objectIndex) {\n switch (picking.indexMode) {\n case INDEX_PICKING_MODE_INSTANCE:\n picking_objectIndex = gl_InstanceID;\n break;\n case INDEX_PICKING_MODE_CUSTOM:\n picking_objectIndex = objectIndex;\n break;\n }\n}\n`;\n\nconst fs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\nconst int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst int COLOR_PICKING_MAX_BATCH_INDEX = 254;\n\nflat in int picking_objectIndex;\n\nbool picking_isFragmentHighlighted() {\n return\n bool(picking.isHighlightActive) &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == picking_objectIndex\n ;\n}\n\nvec4 picking_filterHighlightColor(vec4 color) {\n if (bool(picking.isActive)) {\n return color;\n }\n\n if (!picking_isFragmentHighlighted()) {\n return color;\n }\n\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\nbool picking_canEncodePickInfo(int objectIndex) {\n return\n objectIndex != COLOR_PICKING_INVALID_INDEX &&\n objectIndex >= 0 &&\n objectIndex <= COLOR_PICKING_MAX_OBJECT_INDEX &&\n picking.batchIndex >= 0 &&\n picking.batchIndex <= COLOR_PICKING_MAX_BATCH_INDEX;\n}\n\nvec4 picking_getPickingColor() {\n if (!picking_canEncodePickInfo(picking_objectIndex)) {\n return vec4(0.0);\n }\n\n int encodedObjectIndex = picking_objectIndex + 1;\n int red = encodedObjectIndex % 256;\n int green = (encodedObjectIndex / 256) % 256;\n int blue = (encodedObjectIndex / 65536) % 256;\n int alpha = picking.batchIndex + 1;\n\n return vec4(float(red), float(green), float(blue), float(alpha)) / 255.0;\n}\n\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (!picking_canEncodePickInfo(picking_objectIndex)) {\n discard;\n }\n return picking_getPickingColor();\n }\n\n return color;\n}\n\nvec4 picking_filterColor(vec4 color) {\n vec4 outColor = color;\n outColor = picking_filterHighlightColor(outColor);\n outColor = picking_filterPickingColor(outColor);\n return outColor;\n}\n`;\n\n/**\n * Provides support for object-index based color picking and highlighting.\n */\nexport const picking = {\n ...pickingUniforms,\n name: 'picking',\n source,\n vs,\n fs\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nimport type {PickingBindings, PickingProps, PickingUniforms} from './picking-uniforms';\nimport {pickingUniforms, GLSL_UNIFORMS, WGSL_UNIFORMS, INVALID_INDEX} from './picking-uniforms';\n\nconst source = /* wgsl */ `\\\n${WGSL_UNIFORMS}\n\nconst COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\nconst COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst COLOR_PICKING_MAX_BATCH_INDEX = 254;\n\nfn picking_getInstanceObjectIndex(instanceIndex: u32) -> i32 {\n return i32(instanceIndex);\n}\n\nfn picking_getVertexObjectIndex(vertexIndex: u32) -> i32 {\n return i32(vertexIndex);\n}\n\nfn picking_getAttributeObjectIndex(objectIndex: i32) -> i32 {\n return objectIndex;\n}\n\nfn picking_setObjectIndex(objectIndex: i32) -> i32 {\n return picking_getAttributeObjectIndex(objectIndex);\n}\n\nfn picking_isObjectHighlighted(objectIndex: i32) -> bool {\n return\n picking.isHighlightActive != 0 &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == objectIndex;\n}\n\nfn picking_filterHighlightColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0 || !picking_isObjectHighlighted(objectIndex)) {\n return color;\n }\n\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n if (blendedAlpha == 0.0) {\n return vec4<f32>(color.rgb, 0.0);\n }\n\n let highLightRatio = highLightAlpha / blendedAlpha;\n let blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4<f32>(blendedRGB, blendedAlpha);\n}\n\nfn picking_canEncodePickInfo(objectIndex: i32) -> bool {\n return\n objectIndex != COLOR_PICKING_INVALID_INDEX &&\n objectIndex >= 0 &&\n objectIndex <= COLOR_PICKING_MAX_OBJECT_INDEX &&\n picking.batchIndex >= 0 &&\n picking.batchIndex <= COLOR_PICKING_MAX_BATCH_INDEX;\n}\n\nfn picking_getPickingColor(objectIndex: i32) -> vec4<f32> {\n if (!picking_canEncodePickInfo(objectIndex)) {\n return vec4<f32>(0.0, 0.0, 0.0, 0.0);\n }\n\n let encodedObjectIndex = objectIndex + 1;\n let red = encodedObjectIndex % 256;\n let green = (encodedObjectIndex / 256) % 256;\n let blue = (encodedObjectIndex / 65536) % 256;\n let alpha = picking.batchIndex + 1;\n\n return vec4<f32>(\n f32(red) / 255.0,\n f32(green) / 255.0,\n f32(blue) / 255.0,\n f32(alpha) / 255.0\n );\n}\n\nfn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0) {\n if (!picking_canEncodePickInfo(objectIndex)) {\n discard;\n }\n return picking_getPickingColor(objectIndex);\n }\n\n return color;\n}\n\nfn picking_filterColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n var outColor = color;\n outColor = picking_filterHighlightColor(outColor, objectIndex);\n outColor = picking_filterPickingColor(outColor, objectIndex);\n return outColor;\n}\n`;\n\nconst vs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int INDEX_PICKING_MODE_INSTANCE = 0;\nconst int INDEX_PICKING_MODE_ATTRIBUTE = 1;\nconst int INDEX_PICKING_MODE_VERTEX = 2;\n\nflat out int picking_objectIndex;\n\nvoid picking_setObjectIndex(int objectIndex) {\n switch (picking.indexMode) {\n case INDEX_PICKING_MODE_INSTANCE:\n picking_objectIndex = gl_InstanceID;\n break;\n case INDEX_PICKING_MODE_ATTRIBUTE:\n picking_objectIndex = objectIndex;\n break;\n case INDEX_PICKING_MODE_VERTEX:\n picking_objectIndex = gl_VertexID;\n break;\n }\n}\n`;\n\nconst fs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\nconst int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst int COLOR_PICKING_MAX_BATCH_INDEX = 254;\n\nflat in int picking_objectIndex;\n\nbool picking_isFragmentHighlighted() {\n return\n bool(picking.isHighlightActive) &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == picking_objectIndex\n ;\n}\n\nvec4 picking_filterHighlightColor(vec4 color) {\n if (bool(picking.isActive)) {\n return color;\n }\n\n if (!picking_isFragmentHighlighted()) {\n return color;\n }\n\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\nbool picking_canEncodePickInfo(int objectIndex) {\n return\n objectIndex != COLOR_PICKING_INVALID_INDEX &&\n objectIndex >= 0 &&\n objectIndex <= COLOR_PICKING_MAX_OBJECT_INDEX &&\n picking.batchIndex >= 0 &&\n picking.batchIndex <= COLOR_PICKING_MAX_BATCH_INDEX;\n}\n\nvec4 picking_getPickingColor() {\n if (!picking_canEncodePickInfo(picking_objectIndex)) {\n return vec4(0.0);\n }\n\n int encodedObjectIndex = picking_objectIndex + 1;\n int red = encodedObjectIndex % 256;\n int green = (encodedObjectIndex / 256) % 256;\n int blue = (encodedObjectIndex / 65536) % 256;\n int alpha = picking.batchIndex + 1;\n\n return vec4(float(red), float(green), float(blue), float(alpha)) / 255.0;\n}\n\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (!picking_canEncodePickInfo(picking_objectIndex)) {\n discard;\n }\n return picking_getPickingColor();\n }\n\n return color;\n}\n\nvec4 picking_filterColor(vec4 color) {\n vec4 outColor = color;\n outColor = picking_filterHighlightColor(outColor);\n outColor = picking_filterPickingColor(outColor);\n return outColor;\n}\n`;\n\n/**\n * Provides object-index based color picking and highlighting.\n */\nexport const picking = {\n ...pickingUniforms,\n name: 'picking',\n source,\n vs,\n fs\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nimport type {PickingBindings, PickingProps, PickingUniforms} from './picking-uniforms';\nimport {pickingUniforms, GLSL_UNIFORMS, WGSL_UNIFORMS, INVALID_INDEX} from './picking-uniforms';\n\n// SHADERS\n\nconst source = /* wgsl */ `\\\n${WGSL_UNIFORMS}\n\nconst INDEX_PICKING_MODE_INSTANCE = 0;\nconst INDEX_PICKING_MODE_ATTRIBUTE = 1;\nconst INDEX_PICKING_MODE_VERTEX = 2;\nconst INDEX_PICKING_INVALID_INDEX = ${INVALID_INDEX}; // 2^32 - 1\n\n/**\n * WGSL shaders need to carry the returned object index through their own stage outputs.\n */\nfn picking_getInstanceObjectIndex(instanceIndex: u32) -> i32 {\n return i32(instanceIndex);\n}\n\nfn picking_getVertexObjectIndex(vertexIndex: u32) -> i32 {\n return i32(vertexIndex);\n}\n\nfn picking_getAttributeObjectIndex(objectIndex: i32) -> i32 {\n return objectIndex;\n}\n\nfn picking_setObjectIndex(objectIndex: i32) -> i32 {\n return picking_getAttributeObjectIndex(objectIndex);\n}\n\nfn picking_isObjectHighlighted(objectIndex: i32) -> bool {\n return\n picking.isHighlightActive != 0 &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == objectIndex;\n}\n\nfn picking_filterHighlightColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0 || !picking_isObjectHighlighted(objectIndex)) {\n return color;\n }\n\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n if (blendedAlpha == 0.0) {\n return vec4<f32>(color.rgb, 0.0);\n }\n\n let highLightRatio = highLightAlpha / blendedAlpha;\n let blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4<f32>(blendedRGB, blendedAlpha);\n}\n\nfn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0 && objectIndex == INDEX_PICKING_INVALID_INDEX) {\n discard;\n }\n return color;\n}\n\nfn picking_getPickingColor(objectIndex: i32) -> vec2<i32> {\n return vec2<i32>(objectIndex, picking.batchIndex);\n}\n\n`;\n\nconst vs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int INDEX_PICKING_MODE_INSTANCE = 0;\nconst int INDEX_PICKING_MODE_ATTRIBUTE = 1;\nconst int INDEX_PICKING_MODE_VERTEX = 2;\n\nconst int INDEX_PICKING_INVALID_INDEX = ${INVALID_INDEX}; // 2^32 - 1\n\nflat out int picking_objectIndex;\n\n/**\n * Vertex shaders should call this function to set the object index.\n * If using instance or vertex mode, the argument is ignored and 0 can be supplied.\n */\nvoid picking_setObjectIndex(int objectIndex) {\n switch (picking.indexMode) {\n case INDEX_PICKING_MODE_INSTANCE:\n picking_objectIndex = gl_InstanceID;\n break;\n case INDEX_PICKING_MODE_ATTRIBUTE:\n picking_objectIndex = objectIndex;\n break;\n case INDEX_PICKING_MODE_VERTEX:\n picking_objectIndex = gl_VertexID;\n break;\n }\n}\n`;\n\nconst fs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int INDEX_PICKING_INVALID_INDEX = ${INVALID_INDEX}; // 2^32 - 1\n\nflat in int picking_objectIndex;\n\n/**\n * Check if this vertex is highlighted (part of the selected batch and object)\n */ \nbool picking_isFragmentHighlighted() {\n return \n bool(picking.isHighlightActive) &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == picking_objectIndex\n ;\n}\n\n/**\n * Returns highlight color if this item is selected.\n */\nvec4 picking_filterHighlightColor(vec4 color) {\n // If we are still picking, we don't highlight\n if (bool(picking.isActive)) {\n return color;\n }\n\n // If we are not highlighted, return color as is\n if (!picking_isFragmentHighlighted()) {\n return color;\n }\n \n // Blend in highlight color based on its alpha value\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\n/*\n * Returns picking color if picking enabled else unmodified argument.\n */\nivec4 picking_getPickingColor() {\n // Assumes that colorAttachment0 is rg32int\n // TODO? - we could render indices into a second color attachment and not mess with fragColor\n return ivec4(picking_objectIndex, picking.batchIndex, 0, 0);\n}\n\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (picking_objectIndex == INDEX_PICKING_INVALID_INDEX) {\n discard;\n }\n }\n return color;\n}\n\n/*\n * Returns picking color if picking is enabled if not\n * highlight color if this item is selected, otherwise unmodified argument.\n */\nvec4 picking_filterColor(vec4 color) {\n vec4 outColor = color;\n outColor = picking_filterHighlightColor(outColor);\n outColor = picking_filterPickingColor(outColor);\n return outColor;\n}\n`;\n\n/**\n * Provides support for color-based picking and highlighting.\n *\n * In particular, supports picking a specific instance in an instanced\n * draw call and highlighting an instance based on its picking color,\n * and correspondingly, supports picking and highlighting groups of\n * primitives with the same picking color in non-instanced draw-calls\n *\n * @note Color based picking has the significant advantage in that it can be added to any\n * existing shader without requiring any additional picking logic.\n */\nexport const picking = {\n ...pickingUniforms,\n name: 'picking',\n source,\n vs,\n fs\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport type {Device} from '@luma.gl/core';\n\nimport type {PickingBindings, PickingProps, PickingUniforms} from './picking-uniforms';\nimport {pickingUniforms} from './picking-uniforms';\nimport {picking as colorPicking} from './color-picking';\nimport {picking as indexColorPicking} from './index-color-picking';\nimport {picking as indexPicking} from './index-picking';\nimport {supportsIndexPicking} from './picking-manager';\n\n/**\n * Unified object-picking shader module.\n * Uses color picking on GLSL/WebGL paths and index picking on WGSL/WebGPU paths.\n */\nexport const picking = {\n ...pickingUniforms,\n name: 'picking',\n source: indexPicking.source,\n vs: colorPicking.vs,\n fs: colorPicking.fs\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n\n/** Returns the object-index picking shader module supported by this device. */\nexport function getIndexPickingModule(device: Device): typeof indexPicking {\n return (supportsIndexPicking(device) ? indexPicking : indexColorPicking) as typeof indexPicking;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Framebuffer} from '@luma.gl/core';\nimport {picking} from '@luma.gl/shadertools';\nimport {ShaderInputs} from '../../shader-inputs';\nimport {NumberArray3} from '@math.gl/types';\n\n/**\n * Helper class for using the legacy picking module\n */\nexport class LegacyPickingManager {\n device: Device;\n framebuffer: Framebuffer | null = null;\n shaderInputs: ShaderInputs<{picking: typeof picking.props}>;\n\n constructor(device: Device, shaderInputs: ShaderInputs) {\n this.device = device;\n this.shaderInputs = shaderInputs as ShaderInputs<{picking: typeof picking.props}>;\n }\n\n destroy() {\n this.framebuffer?.destroy();\n }\n\n getFramebuffer() {\n if (!this.framebuffer) {\n this.framebuffer = this.device.createFramebuffer({\n colorAttachments: ['rgba8unorm'],\n depthStencilAttachment: 'depth24plus'\n });\n }\n return this.framebuffer;\n }\n\n /** Clear highlighted / picked object */\n clearPickState() {\n this.shaderInputs.setProps({picking: {highlightedObjectColor: null}});\n }\n\n /** Prepare for rendering picking colors */\n beginRenderPass() {\n const framebuffer = this.getFramebuffer();\n framebuffer.resize(this.device.getCanvasContext().getDevicePixelSize());\n\n this.shaderInputs.setProps({picking: {isActive: true}});\n\n const pickingPass = this.device.beginRenderPass({\n framebuffer,\n clearColor: [0, 0, 0, 0],\n clearDepth: 1\n });\n\n return pickingPass;\n }\n\n updatePickState(mousePosition: [number, number]) {\n const framebuffer = this.getFramebuffer();\n\n // use the center pixel location in device pixel range\n const [pickX, pickY] = this.getPickPosition(mousePosition);\n\n // Read back\n const color255 = this.device.readPixelsToArrayWebGL(framebuffer, {\n sourceX: pickX,\n sourceY: pickY,\n sourceWidth: 1,\n sourceHeight: 1\n });\n // console.log(color255);\n\n // Check if we have\n let highlightedObjectColor: NumberArray3 | null = [...color255].map(\n x => x / 255\n ) as NumberArray3;\n const isHighlightActive =\n highlightedObjectColor[0] + highlightedObjectColor[1] + highlightedObjectColor[2] > 0;\n\n if (!isHighlightActive) {\n highlightedObjectColor = null;\n }\n\n this.shaderInputs.setProps({\n picking: {isActive: false, highlightedObjectColor}\n });\n }\n\n /**\n * Get pick position in device pixel range\n * use the center pixel location in device pixel range\n */\n getPickPosition(mousePosition: [number, number]): [number, number] {\n const devicePixels = this.device.getCanvasContext().cssToDevicePixels(mousePosition);\n const pickX = devicePixels.x + Math.floor(devicePixels.width / 2);\n const pickY = devicePixels.y + Math.floor(devicePixels.height / 2);\n return [pickX, pickY];\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {picking as shadertoolsPicking} from '@luma.gl/shadertools';\n\n/** @deprecated Use `picking`/`colorPicking` for object picking. */\nexport const legacyColorPicking = shadertoolsPicking;\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;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A,YAAY,CAAC,GAAG,GAAG,GAAG,CAAC;MACvB,YAAY;KACb;AAED,WAAO;EACT;EAEA,gBAAgB,eAA+B;AAC7C,UAAM,cAAc,KAAK,eAAc;AAGvC,UAAM,CAAC,OAAO,KAAK,IAAI,KAAK,gBAAgB,aAAa;AAGzD,UAAM,WAAW,KAAK,OAAO,uBAAuB,aAAa;MAC/D,SAAS;MACT,SAAS;MACT,aAAa;MACb,cAAc;KACf;AAID,QAAI,yBAA8C,CAAC,GAAG,QAAQ,EAAE,IAC9D,OAAK,IAAI,GAAG;AAEd,UAAM,oBACJ,uBAAuB,CAAC,IAAI,uBAAuB,CAAC,IAAI,uBAAuB,CAAC,IAAI;AAEtF,QAAI,CAAC,mBAAmB;AACtB,+BAAyB;IAC3B;AAEA,SAAK,aAAa,SAAS;MACzB,SAAS,EAAC,UAAU,OAAO,uBAAsB;KAClD;EACH;;;;;EAMA,gBAAgB,eAA+B;AAC7C,UAAM,eAAe,KAAK,OAAO,iBAAgB,EAAG,kBAAkB,aAAa;AACnF,UAAM,QAAQ,aAAa,IAAI,KAAK,MAAM,aAAa,QAAQ,CAAC;AAChE,UAAM,QAAQ,aAAa,IAAI,KAAK,MAAM,aAAa,SAAS,CAAC;AACjE,WAAO,CAAC,OAAO,KAAK;EACtB;;;;AC7FF,IAAAC,sBAA4C;AAGrC,IAAM,qBAAqB,oBAAAC;;;A7D2K3B,IAAM,eAAe;",
|
|
4
|
+
"sourcesContent": ["// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// luma.gl Engine API\n\n// Animation\nexport type {AnimationClipControllerProps} from './animation/animator';\nexport {AnimationClipController, Animator} from './animation/animator';\nexport {Timeline} from './animation/timeline';\nexport {KeyFrames} from './animation/key-frames';\nexport type {AnimationProps} from './animation-loop/animation-props';\n\nexport {AnimationLoopTemplate} from './animation-loop/animation-loop-template';\n\nexport type {\n AnimationFrameCallback,\n AnimationFrameProvider,\n AnimationLoopProps\n} from './animation-loop/animation-loop';\nexport {AnimationLoop} from './animation-loop/animation-loop';\n\nexport type {MakeAnimationLoopProps} from './animation-loop/make-animation-loop';\nexport {makeAnimationLoop} from './animation-loop/make-animation-loop';\n\nexport type {ModelProps} from './model/model';\nexport {Model} from './model/model';\nexport type {MaterialProps} from './material/material';\nexport {Material} from './material/material';\nexport type {MaterialFactoryProps} from './material/material-factory';\nexport {MaterialFactory} from './material/material-factory';\n\n// Transforms\nexport type {BufferTransformProps} from './compute/buffer-transform';\nexport {BufferTransform} from './compute/buffer-transform';\nexport type {TextureTransformProps} from './compute/texture-transform';\nexport {TextureTransform} from './compute/texture-transform';\n\n// Models\nexport type {ClipSpaceProps} from './models/clip-space';\nexport {ClipSpace} from './models/clip-space';\nexport type {BackgroundTextureModelProps} from './models/billboard-texture-model';\nexport {BackgroundTextureModel} from './models/billboard-texture-model';\nexport type {\n BaseLightModelProps,\n PointLightModelProps,\n SpotLightModelProps,\n DirectionalLightModelProps\n} from './models/light-model-utils';\nexport {PointLightModel} from './models/point-light-model';\nexport {SpotLightModel} from './models/spot-light-model';\nexport {DirectionalLightModel} from './models/directional-light-model';\n\n// Scenegraph Core nodes\nexport {ScenegraphNode} from './scenegraph/scenegraph-node';\nexport type {ScenegraphBounds} from './scenegraph/scenegraph-bounds';\nexport type {\n DepthSortedTraversalContext,\n DepthSortedTraversalOptions,\n GroupNodeProps\n} from './scenegraph/group-node';\nexport {GroupNode} from './scenegraph/group-node';\nexport type {ModelNodeProps} from './scenegraph/model-node';\nexport {ModelNode} from './scenegraph/model-node';\n\n// Geometries\nexport type {GeometryProps, GeometryAttribute, GeometryAttributeInput} from './geometry/geometry';\nexport {Geometry} from './geometry/geometry';\nexport type {MakeInterleavedGeometryOptions} from './geometry/geometry-utils';\nexport {makeInterleavedGeometry} from './geometry/geometry-utils';\nexport type {GPUGeometryProps} from './geometry/gpu-geometry';\nexport {GPUGeometry} from './geometry/gpu-geometry';\n\n// Primitives\nexport type {ConeGeometryProps} from './geometries/cone-geometry';\nexport {ConeGeometry} from './geometries/cone-geometry';\nexport type {CubeGeometryProps} from './geometries/cube-geometry';\nexport {CubeGeometry} from './geometries/cube-geometry';\nexport type {CylinderGeometryProps} from './geometries/cylinder-geometry';\nexport {CylinderGeometry} from './geometries/cylinder-geometry';\nexport type {IcoSphereGeometryProps} from './geometries/ico-sphere-geometry';\nexport {IcoSphereGeometry} from './geometries/ico-sphere-geometry';\nexport type {PlaneGeometryProps} from './geometries/plane-geometry';\nexport {PlaneGeometry} from './geometries/plane-geometry';\nexport type {SphereGeometryProps} from './geometries/sphere-geometry';\nexport {SphereGeometry} from './geometries/sphere-geometry';\nexport type {TruncatedConeGeometryProps} from './geometries/truncated-cone-geometry';\nexport {TruncatedConeGeometry} from './geometries/truncated-cone-geometry';\n\nexport {ShaderInputs} from './shader-inputs';\nexport type {ShaderInputBinding, ShaderInputsProps} from './shader-inputs';\n\n// Application Utilities\nexport {makeRandomGenerator} from './application-utils/random';\nexport {\n setPathPrefix,\n loadImage,\n loadImageBitmap,\n _resolveLoadFileUrl\n} from './application-utils/load-file';\n\n// Dynamic Resources\n\nexport type {\n TextureCubeFace,\n TextureImageData,\n Texture1DData,\n Texture2DData,\n Texture3DData,\n TextureCubeData,\n TextureArrayData,\n TextureCubeArrayData\n} from './dynamic-texture/texture-data';\n\nexport type {DynamicTextureProps} from './dynamic-texture/dynamic-texture';\nexport {DynamicTexture} from './dynamic-texture/dynamic-texture';\nexport type {\n TextureBindingLayout,\n TextureBindingSource\n} from './dynamic-texture/texture-binding-source';\nexport type {VideoTextureProps} from './dynamic-texture/video-texture';\nexport {VideoTexture} from './dynamic-texture/video-texture';\nexport type {\n BufferBindingSource,\n DynamicBufferProps,\n DynamicBufferRange\n} from './dynamic-buffer/dynamic-buffer';\nexport {DynamicBuffer} from './dynamic-buffer/dynamic-buffer';\n\n// EXPERIMENTAL\nexport type {\n ShaderPassBinding,\n ShaderPassRendererProps,\n ShaderPassRendererRenderOptions,\n ShaderPassSourceTexture\n} from './passes/shader-pass-renderer';\nexport {ShaderPassRenderer} from './passes/shader-pass-renderer';\n\nexport {Swap} from './compute/swap';\nexport {SwapBuffers} from './compute/swap';\nexport {SwapFramebuffers} from './compute/swap';\n\nexport type {ComputationProps} from './compute/computation';\nexport {Computation} from './compute/computation';\n\nexport type {\n PickInfo,\n PickingTooltip,\n PickingMode,\n ResolvedPickingMode,\n PickingShouldPickOptions,\n PickingBackend,\n PickingManagerProps,\n ResolvedPickingBackend\n} from './modules/picking/picking-manager';\nexport {\n PickingManager,\n supportsIndexPicking,\n resolvePickingMode,\n resolvePickingBackend\n} from './modules/picking/picking-manager';\nexport {getIndexPickingModule, picking} from './modules/picking/picking';\nexport {picking as indexPicking} from './modules/picking/index-picking';\nexport {picking as indexColorPicking} from './modules/picking/index-color-picking';\nexport {picking as colorPicking} from './modules/picking/color-picking';\n\nexport {\n requestAnimationFramePolyfill,\n cancelAnimationFramePolyfill\n} from './animation-loop/request-animation-frame';\n\n// DEPRECATED\n\nexport {LegacyPickingManager} from './modules/picking/legacy-picking-manager';\nexport {legacyColorPicking} from './modules/picking/legacy-color-picking';\n\nimport {DynamicTexture, type DynamicTextureProps} from './dynamic-texture/dynamic-texture';\n/** @deprecated use DynamicTexture */\nexport const AsyncTexture = DynamicTexture;\n/** @deprecated use DynamicTextureProps */\nexport type AsyncTextureProps = DynamicTextureProps;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '@luma.gl/core';\n\n/** Construction props shared by all animation clip controllers. */\nexport type AnimationClipControllerProps = {\n /** Application-visible clip name. */\n name?: string;\n /** Start time in seconds relative to wall-clock playback time. */\n startTime?: number;\n /** Whether playback is active. */\n playing?: boolean;\n /** Playback speed multiplier. */\n speed?: number;\n};\n\n/** Generic playback controller for one animation clip. */\nexport abstract class AnimationClipController {\n /** Application-visible clip name. */\n name: string;\n /** Whether playback is currently enabled. */\n playing: boolean = true;\n /** Playback speed multiplier. */\n speed: number = 1;\n /** Start time in seconds relative to wall-clock playback time. */\n startTime: number = 0;\n\n constructor(props: AnimationClipControllerProps = {}) {\n this.name = props.name || 'unnamed';\n Object.assign(this, props);\n }\n\n /** Advances the clip to the supplied wall-clock time in milliseconds. */\n setTime(timeMs: number): void {\n if (!this.playing) {\n return;\n }\n\n const absoluteTimeSeconds = timeMs / 1000;\n const localTimeSeconds = (absoluteTimeSeconds - this.startTime) * this.speed;\n this.applyTime(localTimeSeconds);\n }\n\n /** Applies the resolved local clip time in seconds. */\n protected abstract applyTime(localTimeSeconds: number): void;\n}\n\n/** Generic manager for a set of time-driven animation clips. */\nexport class Animator<TClip extends AnimationClipController> {\n /** Managed clip list. */\n readonly clips: TClip[];\n /** Compatibility alias for clip list. */\n readonly animations: TClip[];\n\n constructor(clips: TClip[]) {\n this.clips = clips;\n this.animations = clips;\n }\n\n /** @deprecated Use .setTime(). */\n animate(timeMs: number): void {\n log.warn(\n `${this.constructor.name}#animate is deprecated. Use ${this.constructor.name}#setTime instead`\n )();\n this.setTime(timeMs);\n }\n\n /** Advances every clip to the supplied wall-clock time in milliseconds. */\n setTime(timeMs: number): void {\n this.clips.forEach(clip => clip.setTime(timeMs));\n }\n\n /** Returns the managed animation clips. */\n getAnimations(): TClip[] {\n return this.clips;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Timeline channel properties\n * @param delay = 0;\n * @param duration = Number.POSITIVE_INFINITY;\n * @param rate = 1\n * @param repeat = 1\n */\nexport type ChannelOptions = {\n delay?: number;\n duration?: number;\n rate?: number;\n repeat?: number;\n};\n\nexport type AnimationOptions = {\n setTime: (time: number) => void;\n};\n\ntype Channel = {\n time: number;\n delay: number;\n duration: number;\n rate: number;\n repeat: number;\n};\n\ntype Animation = {\n channel?: number;\n animation: {\n setTime: (time: number) => void;\n };\n};\n\nlet channelHandles = 1;\nlet animationHandles = 1;\n\nexport class Timeline {\n time: number = 0;\n channels = new Map<number, Channel>();\n animations = new Map<number, Animation>();\n playing: boolean = false;\n lastEngineTime: number = -1;\n\n constructor() {}\n\n addChannel(props: ChannelOptions): number {\n const {delay = 0, duration = Number.POSITIVE_INFINITY, rate = 1, repeat = 1} = props;\n\n const channelId = channelHandles++;\n const channel: Channel = {\n time: 0,\n delay,\n duration,\n rate,\n repeat\n };\n this._setChannelTime(channel, this.time);\n this.channels.set(channelId, channel);\n\n return channelId;\n }\n\n removeChannel(channelId: number): void {\n this.channels.delete(channelId);\n\n for (const [animationHandle, animation] of this.animations) {\n if (animation.channel === channelId) {\n this.detachAnimation(animationHandle);\n }\n }\n }\n\n isFinished(channelId: number): boolean {\n const channel = this.channels.get(channelId);\n if (channel === undefined) {\n return false;\n }\n\n return this.time >= channel.delay + channel.duration * channel.repeat;\n }\n\n getTime(channelId?: number): number {\n if (channelId === undefined) {\n return this.time;\n }\n\n const channel = this.channels.get(channelId);\n\n if (channel === undefined) {\n return -1;\n }\n\n return channel.time;\n }\n\n setTime(time: number): void {\n this.time = Math.max(0, time);\n\n const channels = this.channels.values();\n for (const channel of channels) {\n this._setChannelTime(channel, this.time);\n }\n\n const animations = this.animations.values();\n for (const animationData of animations) {\n const {animation, channel} = animationData;\n animation.setTime(this.getTime(channel));\n }\n }\n\n play(): void {\n this.playing = true;\n }\n\n pause(): void {\n this.playing = false;\n this.lastEngineTime = -1;\n }\n\n reset(): void {\n this.setTime(0);\n }\n\n attachAnimation(animation: AnimationOptions, channelHandle?: number): number {\n const animationHandle = animationHandles++;\n\n this.animations.set(animationHandle, {\n animation,\n channel: channelHandle\n });\n\n animation.setTime(this.getTime(channelHandle));\n\n return animationHandle;\n }\n\n detachAnimation(channelId: number): void {\n this.animations.delete(channelId);\n }\n\n update(engineTime: number): void {\n if (this.playing) {\n if (this.lastEngineTime === -1) {\n this.lastEngineTime = engineTime;\n }\n this.setTime(this.time + (engineTime - this.lastEngineTime));\n this.lastEngineTime = engineTime;\n }\n }\n\n _setChannelTime(channel: Channel, time: number): void {\n const offsetTime = time - channel.delay;\n const totalDuration = channel.duration * channel.repeat;\n // Note(Tarek): Don't loop on final repeat.\n if (offsetTime >= totalDuration) {\n channel.time = channel.duration * channel.rate;\n } else {\n channel.time = Math.max(0, offsetTime) % channel.duration;\n channel.time *= channel.rate;\n }\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// keyframes\nexport type KeyFrame<T> = [number, T];\n\n/** Holds a list of key frames (timestamped values) */\nexport class KeyFrames<T = number> {\n startIndex: number = -1;\n endIndex: number = -1;\n factor: number = 0;\n times: number[] = [];\n values: T[] = [];\n private _lastTime = -1;\n\n constructor(keyFrames: KeyFrame<T>[]) {\n this.setKeyFrames(keyFrames);\n this.setTime(0);\n }\n\n setKeyFrames(keyFrames: KeyFrame<T>[]): void {\n const numKeys = keyFrames.length;\n this.times.length = numKeys;\n this.values.length = numKeys;\n\n for (let i = 0; i < numKeys; ++i) {\n this.times[i] = keyFrames[i][0];\n this.values[i] = keyFrames[i][1];\n }\n\n this._calculateKeys(this._lastTime);\n }\n\n setTime(time: number): void {\n time = Math.max(0, time);\n\n if (time !== this._lastTime) {\n this._calculateKeys(time);\n this._lastTime = time;\n }\n }\n\n getStartTime(): number {\n return this.times[this.startIndex];\n }\n\n getEndTime(): number {\n return this.times[this.endIndex];\n }\n\n getStartData(): T {\n return this.values[this.startIndex];\n }\n\n getEndData(): T {\n return this.values[this.endIndex];\n }\n\n _calculateKeys(time: number): void {\n let index = 0;\n const numKeys = this.times.length;\n\n for (index = 0; index < numKeys - 2; ++index) {\n if (this.times[index + 1] > time) {\n break;\n }\n }\n\n this.startIndex = index;\n this.endIndex = index + 1;\n\n const startTime = this.times[this.startIndex];\n const endTime = this.times[this.endIndex];\n this.factor = Math.min(Math.max(0, (time - startTime) / (endTime - startTime)), 1);\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {AnimationProps} from './animation-props';\n\n/**\n * Minimal class that represents a \"componentized\" rendering life cycle\n * (resource construction, repeated rendering, resource destruction)\n *\n * @note A motivation for this class compared to the raw animation loop is\n * that it simplifies TypeScript code by allowing resources to be typed unconditionally\n * since they are allocated in the constructor rather than in onInitialized\n *\n * @note Introduced in luma.gl v9\n *\n * @example AnimationLoopTemplate is intended to be subclassed,\n * but the subclass should not be instantiated directly. Instead the subclass\n * (i.e. the constructor of the subclass) should be used\n * as an argument to create an AnimationLoop.\n */\nexport abstract class AnimationLoopTemplate {\n constructor(animationProps?: AnimationProps) {}\n async onInitialize(animationProps: AnimationProps): Promise<unknown> {\n return null;\n }\n abstract onRender(animationProps: AnimationProps): unknown;\n abstract onFinalize(animationProps: AnimationProps): void;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {luma, Device} from '@luma.gl/core';\nimport {\n requestAnimationFramePolyfill,\n cancelAnimationFramePolyfill\n} from './request-animation-frame';\nimport {Timeline} from '../animation/timeline';\nimport {AnimationProps} from './animation-props';\nimport {Stats, Stat} from '@probe.gl/stats';\n\nlet statIdCounter = 0;\nconst ANIMATION_LOOP_STATS = 'Animation Loop';\n\n/** Experimental v10 callback shape for browser or custom animation frames. */\nexport type AnimationFrameCallback = (time: DOMHighResTimeStamp, animationFrame?: unknown) => void;\n\n/** Experimental v10 work-in-progress animation frame source. */\nexport interface AnimationFrameProvider {\n requestAnimationFrame(callback: AnimationFrameCallback): number;\n cancelAnimationFrame(animationFrameId: number): void;\n}\n\nconst defaultAnimationFrameProvider: AnimationFrameProvider = {\n requestAnimationFrame: callback => requestAnimationFramePolyfill(callback),\n cancelAnimationFrame: animationFrameId => cancelAnimationFramePolyfill(animationFrameId)\n};\n\n/** AnimationLoop properties */\nexport type AnimationLoopProps = {\n device: Device | Promise<Device>;\n\n onAddHTML?: (div: HTMLDivElement) => string; // innerHTML\n onInitialize?: (animationProps: AnimationProps) => Promise<unknown>;\n onRender?: (animationProps: AnimationProps) => unknown;\n onFinalize?: (animationProps: AnimationProps) => void;\n onError?: (reason: Error) => void;\n\n stats?: Stats;\n\n // view parameters - TODO move to CanvasContext?\n autoResizeViewport?: boolean;\n /** Experimental v10 work-in-progress frame source. */\n animationFrameProvider?: AnimationFrameProvider;\n};\n\nexport type MutableAnimationLoopProps = {\n // view parameters\n autoResizeViewport?: boolean;\n /** Experimental v10 work-in-progress frame source. */\n animationFrameProvider?: AnimationFrameProvider;\n};\n\n/** Convenient animation loop */\nexport class AnimationLoop {\n static defaultAnimationLoopProps = {\n device: null!,\n\n onAddHTML: () => '',\n onInitialize: async () => null,\n onRender: () => {},\n onFinalize: () => {},\n onError: error => {\n // biome-ignore lint/suspicious/noConsole: default fallback error reporting for app loops.\n console.error(error);\n },\n\n stats: undefined!,\n\n // view parameters\n autoResizeViewport: false,\n animationFrameProvider: defaultAnimationFrameProvider\n } as const satisfies Readonly<Required<AnimationLoopProps>>;\n\n device: Device | null = null;\n canvas: HTMLCanvasElement | OffscreenCanvas | null = null;\n\n props: Required<AnimationLoopProps>;\n animationProps: AnimationProps | null = null;\n timeline: Timeline | null = null;\n stats: Stats;\n sharedStats: Stats;\n cpuTime: Stat;\n gpuTime: Stat;\n frameRate: Stat;\n\n display: any;\n\n private _needsRedraw: string | false = 'initialized';\n\n _initialized: boolean = false;\n _running: boolean = false;\n _animationFrameId: any = null;\n _nextFramePromise: Promise<AnimationLoop> | null = null;\n _resolveNextFrame: ((animationLoop: AnimationLoop) => void) | null = null;\n _cpuStartTime: number = 0;\n _error: Error | null = null;\n _lastFrameTime: number = 0;\n\n /*\n * @param {HTMLCanvasElement} canvas - if provided, width and height will be passed to context\n */\n constructor(props: AnimationLoopProps) {\n this.props = {...AnimationLoop.defaultAnimationLoopProps, ...props};\n props = this.props;\n\n if (!props.device) {\n throw new Error('No device provided');\n }\n\n // state\n this.stats = props.stats || new Stats({id: `animation-loop-${statIdCounter++}`});\n this.sharedStats = luma.stats.get(ANIMATION_LOOP_STATS);\n this.frameRate = this.stats.get('Frame Rate');\n this.frameRate.setSampleSize(1);\n this.cpuTime = this.stats.get('CPU Time');\n this.gpuTime = this.stats.get('GPU Time');\n\n this.setProps({\n autoResizeViewport: props.autoResizeViewport,\n animationFrameProvider: props.animationFrameProvider\n });\n\n // Bind methods\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n\n this._onMousemove = this._onMousemove.bind(this);\n this._onMouseleave = this._onMouseleave.bind(this);\n }\n\n destroy(): void {\n this.stop();\n this._setDisplay(null);\n this.device?._disableDebugGPUTime();\n }\n\n /** @deprecated Use .destroy() */\n delete(): void {\n this.destroy();\n }\n\n reportError(error: Error): void {\n this.props.onError(error);\n this._error = error;\n }\n\n /** Flags this animation loop as needing redraw */\n setNeedsRedraw(reason: string): this {\n this._needsRedraw = this._needsRedraw || reason;\n return this;\n }\n\n /** Query redraw status. Clears the flag. */\n needsRedraw(): false | string {\n const reason = this._needsRedraw;\n this._needsRedraw = false;\n return reason;\n }\n\n setProps(props: MutableAnimationLoopProps): this {\n if ('autoResizeViewport' in props) {\n this.props.autoResizeViewport = props.autoResizeViewport || false;\n }\n if ('animationFrameProvider' in props) {\n const animationFrameProvider = props.animationFrameProvider || defaultAnimationFrameProvider;\n if (animationFrameProvider !== this.props.animationFrameProvider) {\n const animationFrameWasScheduled = this._animationFrameId !== null;\n if (animationFrameWasScheduled) {\n this._cancelAnimationFrame();\n }\n this.props.animationFrameProvider = animationFrameProvider;\n if (animationFrameWasScheduled) {\n this._requestAnimationFrame();\n }\n }\n }\n return this;\n }\n\n /** Starts a render loop if not already running */\n async start() {\n if (this._running) {\n return this;\n }\n this._running = true;\n\n try {\n let appContext;\n if (!this._initialized) {\n this._initialized = true;\n // Create the WebGL context\n await this._initDevice();\n this._initialize();\n if (!this._running) {\n return null;\n }\n\n // Note: onIntialize can return a promise (e.g. in case app needs to load resources)\n await this.props.onInitialize(this._getAnimationProps());\n }\n\n // check that we haven't been stopped\n if (!this._running) {\n return null;\n }\n\n // Start the loop\n if (appContext !== false) {\n // cancel any pending renders to ensure only one loop can ever run\n this._cancelAnimationFrame();\n this._requestAnimationFrame();\n }\n\n return this;\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error('Unknown error');\n this.props.onError(error);\n // this._running = false; // TODO\n throw error;\n }\n }\n\n /** Stops a render loop if already running, finalizing */\n stop() {\n // console.debug(`Stopping ${this.constructor.name}`);\n if (this._running) {\n // call callback\n // If stop is called immediately, we can end up in a state where props haven't been initialized...\n if (this.animationProps && !this._error) {\n this.props.onFinalize(this.animationProps);\n }\n\n this._cancelAnimationFrame();\n this._nextFramePromise = null;\n this._resolveNextFrame = null;\n this._running = false;\n this._lastFrameTime = 0;\n }\n return this;\n }\n\n /** Explicitly draw a frame */\n redraw(time?: number, animationFrame: unknown | null = null): this {\n if (this.device?.isLost || this._error) {\n return this;\n }\n\n this._beginFrameTimers(time);\n\n this._setupFrame();\n if (this.animationProps) {\n this.animationProps.animationFrame = animationFrame;\n }\n this._updateAnimationProps();\n\n this._renderFrame(this._getAnimationProps());\n\n // clear needsRedraw flag\n this._clearNeedsRedraw();\n\n if (this._resolveNextFrame) {\n this._resolveNextFrame(this);\n this._nextFramePromise = null;\n this._resolveNextFrame = null;\n }\n\n this._endFrameTimers();\n\n return this;\n }\n\n /** Add a timeline, it will be automatically updated by the animation loop. */\n attachTimeline(timeline: Timeline): Timeline {\n this.timeline = timeline;\n return this.timeline;\n }\n\n /** Remove a timeline */\n detachTimeline(): void {\n this.timeline = null;\n }\n\n /** Wait until a render completes */\n waitForRender(): Promise<AnimationLoop> {\n this.setNeedsRedraw('waitForRender');\n\n if (!this._nextFramePromise) {\n this._nextFramePromise = new Promise(resolve => {\n this._resolveNextFrame = resolve;\n });\n }\n return this._nextFramePromise;\n }\n\n /** TODO - should use device.deviceContext */\n async toDataURL(): Promise<string> {\n this.setNeedsRedraw('toDataURL');\n await this.waitForRender();\n if (this.canvas instanceof HTMLCanvasElement) {\n return this.canvas.toDataURL();\n }\n throw new Error('OffscreenCanvas');\n }\n\n // PRIVATE METHODS\n\n _initialize(): void {\n this._startEventHandling();\n\n // Initialize the callback data\n this._initializeAnimationProps();\n this._updateAnimationProps();\n\n // Default viewport setup, in case onInitialize wants to render\n this._resizeViewport();\n\n this.device?._enableDebugGPUTime();\n }\n\n _setDisplay(display: any): void {\n if (this.display) {\n this.display.destroy();\n this.display.animationLoop = null;\n }\n\n // store animation loop on the display\n if (display) {\n display.animationLoop = this;\n }\n\n this.display = display;\n }\n\n _requestAnimationFrame(): void {\n if (!this._running) {\n return;\n }\n\n this._animationFrameId = this.props.animationFrameProvider.requestAnimationFrame(\n this._animationFrame.bind(this)\n );\n }\n\n _cancelAnimationFrame(): void {\n if (this._animationFrameId === null) {\n return;\n }\n\n this.props.animationFrameProvider.cancelAnimationFrame(this._animationFrameId);\n this._animationFrameId = null;\n }\n\n _animationFrame(time: number, animationFrame?: unknown): void {\n if (!this._running) {\n return;\n }\n this.redraw(time, animationFrame ?? null);\n this._requestAnimationFrame();\n }\n\n // Called on each frame, can be overridden to call onRender multiple times\n // to support e.g. stereoscopic rendering\n _renderFrame(animationProps: AnimationProps): void {\n // Allow e.g. VR display to render multiple frames.\n if (this.display) {\n this.display._renderFrame(animationProps);\n return;\n }\n\n // call callback\n this.props.onRender(this._getAnimationProps());\n // end callback\n\n // Submit commands (necessary on WebGPU).\n if (this.device) {\n this.device.submit();\n }\n }\n\n _clearNeedsRedraw(): void {\n this._needsRedraw = false;\n }\n\n _setupFrame(): void {\n this._resizeViewport();\n }\n\n // Initialize the object that will be passed to app callbacks\n _initializeAnimationProps(): void {\n const canvasContext = this.device?.getDefaultCanvasContext();\n if (!this.device || !canvasContext) {\n throw new Error('loop');\n }\n\n const canvas = canvasContext?.canvas;\n const useDevicePixels = canvasContext.props.useDevicePixels;\n\n this.animationProps = {\n animationLoop: this,\n\n device: this.device,\n canvasContext,\n canvas,\n // @ts-expect-error Deprecated\n useDevicePixels,\n\n timeline: this.timeline,\n\n needsRedraw: false,\n\n // Placeholders\n width: 1,\n height: 1,\n aspect: 1,\n\n // Animation props\n time: 0,\n startTime: Date.now(),\n engineTime: 0,\n tick: 0,\n tock: 0,\n\n // Experimental\n animationFrame: null,\n _mousePosition: null // Event props\n };\n }\n\n _getAnimationProps(): AnimationProps {\n if (!this.animationProps) {\n throw new Error('animationProps');\n }\n return this.animationProps;\n }\n\n // Update the context object that will be passed to app callbacks\n _updateAnimationProps(): void {\n if (!this.animationProps) {\n return;\n }\n\n // Can this be replaced with canvas context?\n const {width, height, aspect} = this._getSizeAndAspect();\n if (width !== this.animationProps.width || height !== this.animationProps.height) {\n this.setNeedsRedraw('drawing buffer resized');\n }\n if (aspect !== this.animationProps.aspect) {\n this.setNeedsRedraw('drawing buffer aspect changed');\n }\n\n this.animationProps.width = width;\n this.animationProps.height = height;\n this.animationProps.aspect = aspect;\n\n this.animationProps.needsRedraw = this._needsRedraw;\n\n // Update time properties\n this.animationProps.engineTime = Date.now() - this.animationProps.startTime;\n\n if (this.timeline) {\n this.timeline.update(this.animationProps.engineTime);\n }\n\n this.animationProps.tick = Math.floor((this.animationProps.time / 1000) * 60);\n this.animationProps.tock++;\n\n // For back compatibility\n this.animationProps.time = this.timeline\n ? this.timeline.getTime()\n : this.animationProps.engineTime;\n }\n\n /** Wait for supplied device */\n async _initDevice() {\n this.device = await this.props.device;\n if (!this.device) {\n throw new Error('No device provided');\n }\n this.canvas = this.device.getDefaultCanvasContext().canvas || null;\n // this._createInfoDiv();\n }\n\n _createInfoDiv(): void {\n if (this.canvas && this.props.onAddHTML) {\n const wrapperDiv = document.createElement('div');\n document.body.appendChild(wrapperDiv);\n wrapperDiv.style.position = 'relative';\n const div = document.createElement('div');\n div.style.position = 'absolute';\n div.style.left = '10px';\n div.style.bottom = '10px';\n div.style.width = '300px';\n div.style.background = 'white';\n if (this.canvas instanceof HTMLCanvasElement) {\n wrapperDiv.appendChild(this.canvas);\n }\n wrapperDiv.appendChild(div);\n const html = this.props.onAddHTML(div);\n if (html) {\n div.innerHTML = html;\n }\n }\n }\n\n _getSizeAndAspect(): {width: number; height: number; aspect: number} {\n if (!this.device) {\n return {width: 1, height: 1, aspect: 1};\n }\n // Match projection setup to the actual render target dimensions, which may\n // differ from the CSS size when device-pixel scaling or backend clamping applies.\n const [width, height] = this.device.getDefaultCanvasContext().getDrawingBufferSize();\n const aspect = width > 0 && height > 0 ? width / height : 1;\n\n return {width, height, aspect};\n }\n\n /** @deprecated Default viewport setup */\n _resizeViewport(): void {\n // TODO can we use canvas context to code this in a portable way?\n // @ts-expect-error Expose on canvasContext\n if (this.props.autoResizeViewport && this.device.gl) {\n // @ts-expect-error Expose canvasContext\n this.device.gl.viewport(\n 0,\n 0,\n // @ts-expect-error Expose canvasContext\n this.device.gl.drawingBufferWidth,\n // @ts-expect-error Expose canvasContext\n this.device.gl.drawingBufferHeight\n );\n }\n }\n\n _beginFrameTimers(time?: number) {\n const now = time ?? (typeof performance !== 'undefined' ? performance.now() : Date.now());\n if (this._lastFrameTime) {\n const frameTime = now - this._lastFrameTime;\n if (frameTime > 0) {\n this.frameRate.addTime(frameTime);\n }\n }\n this._lastFrameTime = now;\n\n if (this.device?._isDebugGPUTimeEnabled()) {\n this._consumeEncodedGpuTime();\n }\n\n this.cpuTime.timeStart();\n }\n\n _endFrameTimers() {\n if (this.device?._isDebugGPUTimeEnabled()) {\n this._consumeEncodedGpuTime();\n }\n\n this.cpuTime.timeEnd();\n this._updateSharedStats();\n }\n\n _consumeEncodedGpuTime(): void {\n if (!this.device) {\n return;\n }\n\n const gpuTimeMs = this.device.commandEncoder._gpuTimeMs;\n if (gpuTimeMs !== undefined) {\n this.gpuTime.addTime(gpuTimeMs);\n this.device.commandEncoder._gpuTimeMs = undefined;\n }\n }\n\n _updateSharedStats(): void {\n if (this.stats === this.sharedStats) {\n return;\n }\n\n for (const name of Object.keys(this.sharedStats.stats)) {\n if (!this.stats.stats[name]) {\n delete this.sharedStats.stats[name];\n }\n }\n\n this.stats.forEach(sourceStat => {\n const targetStat = this.sharedStats.get(sourceStat.name, sourceStat.type);\n targetStat.sampleSize = sourceStat.sampleSize;\n targetStat.time = sourceStat.time;\n targetStat.count = sourceStat.count;\n targetStat.samples = sourceStat.samples;\n targetStat.lastTiming = sourceStat.lastTiming;\n targetStat.lastSampleTime = sourceStat.lastSampleTime;\n targetStat.lastSampleCount = sourceStat.lastSampleCount;\n targetStat._count = sourceStat._count;\n targetStat._time = sourceStat._time;\n targetStat._samples = sourceStat._samples;\n targetStat._startTime = sourceStat._startTime;\n targetStat._timerPending = sourceStat._timerPending;\n });\n }\n\n // Event handling\n\n _startEventHandling() {\n if (this.canvas) {\n this.canvas.addEventListener('mousemove', this._onMousemove.bind(this));\n this.canvas.addEventListener('mouseleave', this._onMouseleave.bind(this));\n }\n }\n\n _onMousemove(event: Event) {\n if (event instanceof MouseEvent) {\n this._getAnimationProps()._mousePosition = [event.offsetX, event.offsetY];\n }\n }\n\n _onMouseleave(event: Event) {\n this._getAnimationProps()._mousePosition = null;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global window, setTimeout, clearTimeout */\n\n/** Node.js polyfill for requestAnimationFrame */\n// / <reference types=\"@types/node\" />\nexport function requestAnimationFramePolyfill(callback: (time?: any) => void): any {\n const browserRequestAnimationFrame =\n typeof window !== 'undefined'\n ? window.requestAnimationFrame ||\n (window as Window & {webkitRequestAnimationFrame?: (cb: FrameRequestCallback) => number})\n .webkitRequestAnimationFrame ||\n (window as Window & {mozRequestAnimationFrame?: (cb: FrameRequestCallback) => number})\n .mozRequestAnimationFrame\n : null;\n\n if (browserRequestAnimationFrame) {\n return browserRequestAnimationFrame.call(window, callback);\n }\n\n return setTimeout(\n () => callback(typeof performance !== 'undefined' ? performance.now() : Date.now()),\n 1000 / 60\n );\n}\n\n/** Node.js polyfill for cancelAnimationFrame */\nexport function cancelAnimationFramePolyfill(timerId: any): void {\n const browserCancelAnimationFrame =\n typeof window !== 'undefined'\n ? window.cancelAnimationFrame ||\n (window as Window & {webkitCancelAnimationFrame?: (handle: number) => void})\n .webkitCancelAnimationFrame ||\n (window as Window & {mozCancelAnimationFrame?: (handle: number) => void})\n .mozCancelAnimationFrame\n : null;\n\n if (browserCancelAnimationFrame) {\n browserCancelAnimationFrame.call(window, timerId);\n return;\n }\n\n clearTimeout(timerId);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {luma, Adapter, Device} from '@luma.gl/core';\nimport {AnimationLoopTemplate} from './animation-loop-template';\nimport {AnimationLoop, AnimationLoopProps} from './animation-loop';\nimport type {AnimationProps} from './animation-props';\n\n/** Props accepted while constructing an animation loop from a template. */\nexport type MakeAnimationLoopProps = Omit<\n AnimationLoopProps,\n 'onCreateDevice' | 'onInitialize' | 'onRedraw' | 'onFinalize'\n> & {\n /** List of adapters to use when creating the device */\n adapters?: Adapter[];\n};\n\n/**\n * Instantiates an animation loop and initializes it with the template.\n * @note The application needs to call `start()` on the returned animation loop to start the rendering loop.\n */\nexport function makeAnimationLoop(\n AnimationLoopTemplateCtor: typeof AnimationLoopTemplate,\n props?: MakeAnimationLoopProps\n): AnimationLoop {\n let renderLoop: AnimationLoopTemplate | null = null;\n\n const device =\n props?.device ||\n luma.createDevice({id: 'animation-loop', adapters: props?.adapters, createCanvasContext: true});\n\n // Create an animation loop;\n const animationLoop = new AnimationLoop({\n ...props,\n\n device,\n\n async onInitialize(animationProps: AnimationProps): Promise<unknown> {\n clearError(animationProps.animationLoop.device);\n try {\n // @ts-expect-error abstract to prevent instantiation\n renderLoop = new AnimationLoopTemplateCtor(animationProps);\n // Any async loading can be handled here\n return await renderLoop?.onInitialize(animationProps);\n } catch (error) {\n // biome-ignore lint/suspicious/noConsole: fallback logging before rendering the in-canvas error banner.\n console.error(error);\n renderLoop = null;\n setError(animationProps.animationLoop.device, error as Error);\n animationProps.animationLoop.stop();\n return null;\n }\n },\n\n onRender: (animationProps: AnimationProps) => renderLoop?.onRender(animationProps),\n\n onFinalize: (animationProps: AnimationProps) => renderLoop?.onFinalize(animationProps)\n });\n\n // @ts-expect-error Hack: adds info for the website to find\n animationLoop.getInfo = () => {\n // @ts-ignore\n // eslint-disable-next-line no-invalid-this\n return this.AnimationLoopTemplateCtor.info;\n };\n\n return animationLoop;\n}\n\nfunction setError(device: Device | null, error: Error): void {\n if (!device) {\n return;\n }\n\n const canvas = device.getDefaultCanvasContext().canvas;\n if (canvas instanceof HTMLCanvasElement) {\n canvas.style.overflow = 'visible';\n let errorDiv = document.getElementById('animation-loop-error');\n errorDiv?.remove();\n errorDiv = document.createElement('h1');\n errorDiv.id = 'animation-loop-error';\n errorDiv.innerHTML = error.message;\n errorDiv.style.position = 'absolute';\n errorDiv.style.top = '10px'; // left: 50%; transform: translate(-50%, -50%);';\n errorDiv.style.left = '10px';\n errorDiv.style.color = 'black';\n errorDiv.style.backgroundColor = 'red';\n canvas.parentElement?.appendChild(errorDiv);\n // canvas.style.position = 'absolute';\n }\n}\n\nfunction clearError(device: Device | null): void {\n if (!device) {\n return;\n }\n\n const errorDiv = document.getElementById('animation-loop-error');\n if (errorDiv) {\n errorDiv.remove();\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// A lot of imports, but then Model is where it all comes together...\nimport {type TypedArray} from '@math.gl/types';\nimport {\n type RenderPipelineProps,\n type RenderPipelineParameters,\n type BufferLayout,\n type TextureFormatColor,\n type TextureFormatDepthStencil,\n type Shader,\n type VertexArray,\n type TransformFeedback,\n type CommandEncoder,\n type AttributeInfo,\n type Binding,\n type BindingsByGroup,\n type ComputeShaderLayout,\n type PrimitiveTopology,\n type ShaderLayout,\n type AttributeShaderType,\n Device,\n DeviceFeature,\n Buffer,\n ExternalTexture,\n Texture,\n TextureView,\n RenderPipeline,\n RenderPass,\n PipelineFactory,\n ShaderFactory,\n UniformStore,\n log,\n dataTypeDecoder,\n getAttributeInfosFromLayouts,\n normalizeBindingsByGroup\n} from '@luma.gl/core';\n\nimport type {\n ShaderBindingDebugRow,\n ShaderModule,\n ShaderPlugin,\n PlatformInfo\n} from '@luma.gl/shadertools';\nimport {\n mergeShaderPluginModules,\n resolveShaderPlugins,\n ShaderAssembler\n} from '@luma.gl/shadertools';\n\nimport type {Geometry} from '../geometry/geometry';\nimport {GPUGeometry, makeGPUGeometry} from '../geometry/gpu-geometry';\nimport {getDebugTableForShaderLayout} from '../debug/debug-shader-layout';\nimport {debugFramebuffer} from '../debug/debug-framebuffer';\nimport {deepEqual} from '../utils/deep-equal';\nimport {BufferLayoutHelper} from '../utils/buffer-layout-helper';\nimport {sortedBufferLayoutByShaderSourceLocations} from '../utils/buffer-layout-order';\nimport {\n mergeInferredShaderLayout,\n mergeShaderModules,\n mergeShaderModuleBindingsIntoLayout,\n shaderModuleHasUniforms\n} from '../utils/shader-module-utils';\nimport {uid} from '../utils/uid';\nimport {ShaderInputs} from '../shader-inputs';\nimport {\n DynamicBuffer,\n type DynamicBufferRange,\n isBufferRangeBinding,\n resolveBufferRangeBinding\n} from '../dynamic-buffer/dynamic-buffer';\nimport {\n getTextureBindingLayout,\n isTextureBindingSource,\n type TextureBindingSource\n} from '../dynamic-texture/texture-binding-source';\nimport {Material} from '../material/material';\n\nconst LOG_DRAW_PRIORITY = 2;\nconst LOG_DRAW_TIMEOUT = 10000;\nconst PIPELINE_INITIALIZATION_FAILED = 'render pipeline initialization failed';\nconst DEPTH_STENCIL_ATTACHMENT_FORMATS: TextureFormatDepthStencil[] = [\n 'stencil8',\n 'depth16unorm',\n 'depth24plus',\n 'depth24plus-stencil8',\n 'depth32float',\n 'depth32float-stencil8'\n];\n/** Resource accepted by one model binding slot. */\ntype ModelBinding = Binding | TextureBindingSource | DynamicBuffer | DynamicBufferRange;\ntype ModelBuffer = Buffer | DynamicBuffer;\n/** Shader layout subset needed while resolving texture binding sources. */\ntype AnyShaderLayout = Pick<ShaderLayout | ComputeShaderLayout, 'bindings'>;\n\nexport type ModelProps = Omit<RenderPipelineProps, 'vs' | 'fs' | 'bindings'> & {\n source?: string;\n vs?: string | null;\n fs?: string | null;\n\n /** Shadertools shader modules added to shader code. */\n modules?: ShaderModule<any, any, any>[];\n /** Shadertools boolean or numeric preprocessor defines that configure shader code. */\n defines?: Record<string, boolean | number>;\n /** Reusable shader assembly plugins resolved for the active GLSL or WGSL backend. */\n plugins?: ShaderPlugin[];\n\n /** Shader inputs, used to generate uniform buffers and bindings. */\n shaderInputs?: ShaderInputs;\n /** Material-owned group-3 bindings */\n material?: Material;\n /** Shader resource bindings, including dynamic buffers and dynamic textures. */\n bindings?: Record<string, ModelBinding>;\n /** WebGL-only uniforms */\n uniforms?: Record<string, unknown>;\n /** Parameters that are built into the pipeline */\n parameters?: RenderPipelineParameters;\n\n /** Geometry */\n geometry?: GPUGeometry | Geometry | null;\n\n /** @deprecated Use instanced rendering? Will be auto-detected in 9.1 */\n isInstanced?: boolean;\n /** instance count */\n instanceCount?: number;\n /** Vertex count */\n vertexCount?: number;\n\n /** Optional index buffer. Dynamic buffers are rebound when resized. */\n indexBuffer?: ModelBuffer | null;\n /** Optional indexed draw count. Defaults to the full bound index buffer length. */\n indexCount?: number;\n /** First vertex byte offset for WebGL indexed draws or first vertex for non-indexed draws. */\n firstVertex?: number;\n /** First index element for WebGPU indexed draws. */\n firstIndex?: number;\n /** Buffer-valued attributes. Dynamic buffers are rebound when resized. */\n attributes?: Record<string, ModelBuffer>;\n /** */\n constantAttributes?: Record<string, TypedArray>;\n\n /** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */\n disableWarnings?: boolean;\n\n /** @internal For use with {@link TransformFeedback}, WebGL only. */\n varyings?: string[];\n\n transformFeedback?: TransformFeedback;\n\n /** Show shader source in browser? */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n\n /** Factory used to create a {@link RenderPipeline}. Defaults to {@link Device} default factory. */\n pipelineFactory?: PipelineFactory;\n /** Factory used to create a {@link Shader}. Defaults to {@link Device} default factory. */\n shaderFactory?: ShaderFactory;\n /** Shader assembler. Defaults to the ShaderAssembler.getShaderAssembler() */\n shaderAssembler?: ShaderAssembler;\n};\n\n/**\n * High level draw API for luma.gl.\n *\n * A `Model` encapsulates shaders, geometry attributes, bindings and render\n * pipeline state into a single object. It automatically reuses and rebuilds\n * pipelines as render parameters change and exposes convenient hooks for\n * updating uniforms and attributes.\n *\n * Features:\n * - Reuses and lazily recompiles {@link RenderPipeline | pipelines} as needed.\n * - Integrates with `@luma.gl/shadertools` to assemble GLSL or WGSL from shader modules.\n * - Manages geometry attributes and buffer bindings.\n * - Accepts textures, samplers and uniform buffers as bindings, including texture binding sources.\n * - Provides detailed debug logging and optional shader source inspection.\n */\nexport class Model {\n static defaultProps: Required<ModelProps> = {\n ...RenderPipeline.defaultProps,\n source: undefined!,\n vs: null,\n fs: null,\n id: 'unnamed',\n handle: undefined,\n userData: {},\n defines: {},\n modules: [],\n plugins: [],\n geometry: null,\n indexBuffer: null,\n indexCount: undefined!,\n firstVertex: 0,\n firstIndex: 0,\n attributes: {},\n constantAttributes: {},\n bindings: {},\n uniforms: {},\n varyings: [],\n\n isInstanced: undefined!,\n instanceCount: 0,\n vertexCount: 0,\n\n shaderInputs: undefined!,\n material: undefined!,\n pipelineFactory: undefined!,\n shaderFactory: undefined!,\n transformFeedback: undefined!,\n shaderAssembler: ShaderAssembler.getDefaultShaderAssembler(),\n\n debugShaders: undefined!,\n disableWarnings: undefined!\n };\n\n /** Device that created this model */\n readonly device: Device;\n /** Application provided identifier */\n readonly id: string;\n /** WGSL shader source when using unified shader */\n // @ts-expect-error assigned in function called from constructor\n readonly source: string;\n /** GLSL vertex shader source */\n // @ts-expect-error assigned in function called from constructor\n readonly vs: string;\n /** GLSL fragment shader source */\n // @ts-expect-error assigned in function called from constructor\n readonly fs: string;\n /** Factory used to create render pipelines */\n readonly pipelineFactory: PipelineFactory;\n /** Factory used to create shaders */\n readonly shaderFactory: ShaderFactory;\n /** User-supplied per-model data */\n userData: {[key: string]: any} = {};\n\n // Fixed properties (change can trigger pipeline rebuild)\n\n /** The render pipeline GPU parameters, depth testing etc */\n parameters: RenderPipelineParameters;\n\n /** The primitive topology */\n topology: PrimitiveTopology;\n /** Buffer layout */\n bufferLayout: BufferLayout[];\n\n // Dynamic properties\n\n /** Use instanced rendering */\n isInstanced: boolean | undefined = undefined;\n /** instance count. `undefined` means not instanced */\n instanceCount: number = 0;\n /** Vertex count */\n vertexCount: number;\n /** Indexed draw count override. Undefined draws the full bound index buffer. */\n indexCount: number | undefined;\n /** First vertex byte offset for WebGL indexed draws or first vertex for non-indexed draws. */\n firstVertex: number;\n /** First index element for WebGPU indexed draws. */\n firstIndex: number;\n\n /** Index buffer */\n indexBuffer: Buffer | null = null;\n /** Buffer-valued attributes */\n bufferAttributes: Record<string, Buffer> = {};\n /** Constant-valued attributes */\n constantAttributes: Record<string, TypedArray> = {};\n /** Bindings (textures, samplers, uniform buffers) */\n bindings: Record<string, ModelBinding> = {};\n\n /**\n * VertexArray\n * @note not implemented: if bufferLayout is updated, vertex array has to be rebuilt!\n * @todo - allow application to define multiple vertex arrays?\n * */\n vertexArray: VertexArray;\n\n /** TransformFeedback, WebGL 2 only. */\n transformFeedback: TransformFeedback | null = null;\n\n /** The underlying GPU \"program\". @note May be recreated if parameters change */\n pipeline: RenderPipeline;\n\n /** ShaderInputs instance */\n // @ts-expect-error Assigned in function called by constructor\n shaderInputs: ShaderInputs;\n material: Material | null = null;\n // @ts-expect-error Assigned in function called by constructor\n _uniformStore: UniformStore;\n\n _attributeInfos: Record<string, AttributeInfo> = {};\n _gpuGeometry: GPUGeometry | null = null;\n private props: Required<ModelProps>;\n private _dynamicIndexBufferSource: {source: DynamicBuffer; generation: number} | null = null;\n private _dynamicAttributeBufferSources: Record<\n number,\n {source: DynamicBuffer; generation: number}\n > = {};\n private _colorAttachmentFormats: (TextureFormatColor | null)[] | undefined;\n private _depthStencilAttachmentFormat: TextureFormatDepthStencil | undefined;\n\n _pipelineNeedsUpdate: string | false = 'newly created';\n private _needsRedraw: string | false = 'initializing';\n private _drawBlockedReason: string | false = false;\n private _destroyed = false;\n\n /** \"Time\" of last draw. Monotonically increasing timestamp */\n _lastDrawTimestamp: number = -1;\n private _bindingTable: ShaderBindingDebugRow[] = [];\n\n get [Symbol.toStringTag](): string {\n return 'Model';\n }\n\n toString(): string {\n return `Model(${this.id})`;\n }\n\n constructor(device: Device, props: ModelProps) {\n this.props = {...Model.defaultProps, ...props};\n props = this.props;\n this.id = props.id || uid('model');\n this.device = device;\n\n Object.assign(this.userData, props.userData);\n\n this.material = props.material || null;\n\n const platformInfo = getPlatformInfo(device);\n const resolvedPlugins = resolveShaderPlugins(this.props.plugins, platformInfo.shaderLanguage);\n\n // Setup shader module inputs\n const shaderInputModules = mergeShaderPluginModules(\n this.props.modules,\n resolvedPlugins.modules\n );\n const moduleMap = Object.fromEntries(shaderInputModules.map(module => [module.name, module]));\n\n const shaderInputs =\n props.shaderInputs ||\n new ShaderInputs(moduleMap, {disableWarnings: this.props.disableWarnings});\n if (props.shaderInputs && resolvedPlugins.modules.length > 0) {\n shaderInputs.addModules(resolvedPlugins.modules);\n }\n // @ts-ignore\n this.setShaderInputs(shaderInputs);\n\n // Setup shader assembler\n const modules = mergeShaderModules(this.props.modules, shaderInputs.getModules());\n const defines = {...resolvedPlugins.defines, ...this.props.defines};\n\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(this.props.shaderLayout, modules) || null;\n\n const isWebGPU = this.device.type === 'webgpu';\n\n // WebGPU\n // TODO - hack to support unified WGSL shader\n // TODO - this is wrong, compile a single shader\n if (isWebGPU && this.props.source) {\n // WGSL\n const {source, getUniforms, bindingTable} = this.props.shaderAssembler.assembleWGSLShader({\n platformInfo,\n ...this.props,\n modules,\n defines,\n pluginInjections: resolvedPlugins.injections,\n pluginVertexInputs: resolvedPlugins.vertexInputs,\n pluginVaryings: resolvedPlugins.varyings\n });\n this.source = source;\n // @ts-expect-error\n this._getModuleUniforms = getUniforms;\n this._bindingTable = bindingTable;\n // Extract shader layout after modules have been added to WGSL source, to include any bindings added by modules\n const reflectedShaderLayout = (\n device as Device & {getShaderLayout?: (source: string) => any}\n ).getShaderLayout?.(this.source);\n const inferredShaderLayout = normalizeShaderPluginAttributeNames(\n reflectedShaderLayout,\n resolvedPlugins.vertexInputs\n );\n const shaderLayout = mergeInferredShaderLayout(\n this.props.shaderLayout,\n inferredShaderLayout,\n Object.keys(resolvedPlugins.vertexInputs)\n );\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(shaderLayout || null, modules) || null;\n } else {\n // GLSL\n const {vs, fs, getUniforms} = this.props.shaderAssembler.assembleGLSLShaderPair({\n platformInfo,\n ...this.props,\n modules,\n defines,\n pluginInjections: resolvedPlugins.injections,\n pluginVertexInputs: resolvedPlugins.vertexInputs,\n pluginVaryings: resolvedPlugins.varyings\n });\n\n this.vs = vs;\n this.fs = fs;\n // @ts-expect-error\n this._getModuleUniforms = getUniforms;\n this._bindingTable = [];\n }\n\n this.vertexCount = this.props.vertexCount;\n this.indexCount = this.props.indexCount;\n this.firstVertex = this.props.firstVertex;\n this.firstIndex = this.props.firstIndex;\n this.instanceCount = this.props.instanceCount;\n\n this.topology = this.props.topology;\n this.bufferLayout = this.props.bufferLayout;\n this.parameters = this.props.parameters;\n // Seed attachment formats before creating the initial WebGPU pipeline. This is required for\n // depth-only models whose intentional empty color target list must not fall back to the canvas\n // format before the first render pass can synchronize attachment state.\n this._colorAttachmentFormats = this.props.colorAttachmentFormats;\n this._depthStencilAttachmentFormat = this.props.depthStencilAttachmentFormat;\n\n // Geometry, if provided, sets topology and vertex cound\n if (props.geometry) {\n this.setGeometry(props.geometry);\n }\n\n this.pipelineFactory =\n props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);\n this.shaderFactory = props.shaderFactory || ShaderFactory.getDefaultShaderFactory(this.device);\n\n // Create the pipeline\n // @note order is important\n this.pipeline = this._updatePipeline();\n\n this.vertexArray = device.createVertexArray({\n shaderLayout: this.pipeline.shaderLayout,\n bufferLayout: this.pipeline.bufferLayout\n });\n\n // Now we can apply geometry attributes\n if (this._gpuGeometry) {\n this._setGeometryAttributes(this._gpuGeometry);\n }\n\n // Apply any dynamic settings that will not trigger pipeline change\n if ('isInstanced' in props) {\n this.isInstanced = props.isInstanced;\n }\n\n if (props.instanceCount) {\n this.setInstanceCount(props.instanceCount);\n }\n if (props.vertexCount) {\n this.setVertexCount(props.vertexCount);\n }\n if (props.indexBuffer) {\n this.setIndexBuffer(props.indexBuffer);\n }\n if (props.attributes) {\n this.setAttributes(props.attributes);\n }\n if (props.constantAttributes) {\n this.setConstantAttributes(props.constantAttributes);\n }\n if (props.bindings) {\n this.setBindings(props.bindings);\n }\n if (props.transformFeedback) {\n this.transformFeedback = props.transformFeedback;\n }\n }\n\n destroy(): void {\n if (!this._destroyed) {\n // Release pipeline before we destroy the shaders used by the pipeline\n this.pipelineFactory.release(this.pipeline);\n // Release the shaders\n this.shaderFactory.release(this.pipeline.vs);\n if (this.pipeline.fs && this.pipeline.fs !== this.pipeline.vs) {\n this.shaderFactory.release(this.pipeline.fs);\n }\n this._uniformStore.destroy();\n // TODO - mark resource as managed and destroyIfManaged() ?\n this._gpuGeometry?.destroy();\n this._destroyed = true;\n }\n }\n\n // Draw call\n\n /** Query redraw status. Clears the status. */\n needsRedraw(): false | string {\n // Catch any writes to already bound resources\n if (this._getBindingsUpdateTimestamp() > this._lastDrawTimestamp) {\n this.setNeedsRedraw('contents of bound textures or buffers updated');\n }\n const needsRedraw = this._needsRedraw;\n this._needsRedraw = false;\n return needsRedraw;\n }\n\n /** Mark the model as needing a redraw */\n setNeedsRedraw(reason: string): void {\n this._needsRedraw ||= reason;\n }\n\n /** Returns WGSL binding debug rows for the assembled shader. Returns an empty array for GLSL models. */\n getBindingDebugTable(): readonly ShaderBindingDebugRow[] {\n return this._bindingTable;\n }\n\n /**\n * Updates uniforms and pipeline state before opening a render pass.\n *\n * @param commandEncoder - Encoder that should own any GPU uploads emitted\n * during draw preparation.\n */\n predraw(commandEncoder: CommandEncoder): void {\n // Update uniform buffers if needed\n this._syncDynamicBuffers();\n this.updateShaderInputs(commandEncoder);\n this.material?.updateShaderInputs(commandEncoder);\n // Check if the pipeline is invalidated\n this.pipeline = this._updatePipeline();\n }\n\n /**\n * Issue one draw call.\n * @param renderPass - render pass to draw into\n * @returns `true` if the draw call was executed, `false` if resources were not ready.\n */\n draw(renderPass: RenderPass): boolean {\n if (this._drawBlockedReason && !this._pipelineNeedsUpdate) {\n log.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)();\n return false;\n }\n\n const loadingBinding = this._areBindingsLoading();\n if (loadingBinding) {\n log.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${loadingBinding} not loaded`)();\n return false;\n }\n\n this._syncAttachmentFormats(renderPass);\n\n try {\n renderPass.pushDebugGroup(`${this}.predraw(${renderPass})`);\n if (this.device.type === 'webgpu') {\n // WebGPU uploads cannot be encoded once the render pass is already open.\n // Keep the implicit draw() path working for existing callers by falling\n // back to immediate writes here; callers that need upload ordering\n // across multiple draws/viewports must call predraw(commandEncoder)\n // before beginRenderPass().\n this.updateShaderInputs();\n this.material?.updateShaderInputs();\n this._syncDynamicBuffers();\n this.pipeline = this._updatePipeline();\n } else {\n this.predraw(this.device.commandEncoder);\n }\n } finally {\n renderPass.popDebugGroup();\n }\n\n let drawSuccess: boolean;\n let pipelineErrored = this.pipeline.isErrored;\n try {\n renderPass.pushDebugGroup(`${this}.draw(${renderPass})`);\n this._logDrawCallStart();\n\n // Update the pipeline if invalidated\n // TODO - inside RenderPass is likely the worst place to do this from performance perspective.\n // Application can call Model.predraw() to avoid this.\n this.pipeline = this._updatePipeline();\n pipelineErrored = this.pipeline.isErrored;\n\n if (pipelineErrored) {\n log.info(\n LOG_DRAW_PRIORITY,\n `>>> DRAWING ABORTED ${this.id}: ${PIPELINE_INITIALIZATION_FAILED}`\n )();\n drawSuccess = false;\n } else {\n const drawValidationError = this.vertexArray.getDrawValidationError();\n if (drawValidationError) {\n log.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${drawValidationError}`)();\n this._drawBlockedReason = drawValidationError;\n drawSuccess = false;\n } else {\n const shaderLayout = this._getCurrentShaderLayout();\n const syncBindings = this._getBindings(shaderLayout);\n const syncBindGroups = this._getBindGroups(shaderLayout, syncBindings);\n\n const {indexBuffer} = this.vertexArray;\n const indexCount = indexBuffer\n ? (this.indexCount ??\n indexBuffer.byteLength / (indexBuffer.indexType === 'uint32' ? 4 : 2))\n : undefined;\n\n renderPass.setPipeline(this.pipeline);\n renderPass.setBindings(syncBindGroups, {\n _bindGroupCacheKeys: this._getBindGroupCacheKeys()\n });\n renderPass.setVertexArray(this.vertexArray);\n const hasNoInstances = this.isInstanced === true && this.instanceCount === 0;\n drawSuccess = hasNoInstances\n ? true\n : renderPass.draw({\n isInstanced: this.isInstanced,\n vertexCount: this.vertexCount,\n instanceCount: this.isInstanced ? this.instanceCount : undefined,\n indexCount,\n firstVertex: this.firstVertex,\n firstIndex: this.firstIndex,\n transformFeedback: this.transformFeedback || undefined,\n uniforms: this.props.uniforms,\n // WebGL shares underlying cached programs even for models that have different\n // parameters and topology, so those compatibility overrides remain per draw.\n parameters: this.parameters,\n topology: this.topology\n });\n }\n }\n } finally {\n renderPass.popDebugGroup();\n this._logDrawCallEnd();\n }\n this._logFramebuffer(renderPass);\n\n // Update needsRedraw flag\n if (drawSuccess) {\n this._lastDrawTimestamp = this.device.timestamp;\n this._needsRedraw = false;\n } else if (pipelineErrored) {\n this._needsRedraw = PIPELINE_INITIALIZATION_FAILED;\n this._drawBlockedReason = PIPELINE_INITIALIZATION_FAILED;\n } else if (this._drawBlockedReason) {\n this._needsRedraw = this._drawBlockedReason;\n } else {\n this._needsRedraw = 'waiting for resource initialization';\n }\n return drawSuccess;\n }\n\n // Update fixed fields (can trigger pipeline rebuild)\n\n /**\n * Updates the optional geometry\n * Geometry, set topology and bufferLayout\n * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n setGeometry(geometry: GPUGeometry | Geometry | null): void {\n this._gpuGeometry?.destroy();\n const gpuGeometry = geometry && makeGPUGeometry(this.device, geometry);\n if (gpuGeometry) {\n this.setTopology(gpuGeometry.topology || 'triangle-list');\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n this.bufferLayout = bufferLayoutHelper.mergeBufferLayouts(\n gpuGeometry.bufferLayout,\n this.bufferLayout\n );\n if (this.vertexArray) {\n this._setGeometryAttributes(gpuGeometry);\n }\n }\n this._gpuGeometry = gpuGeometry;\n }\n\n /**\n * Updates the primitive topology ('triangle-list', 'triangle-strip' etc).\n * @note Triggers a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n setTopology(topology: PrimitiveTopology): void {\n if (topology !== this.topology) {\n this.topology = topology;\n this._setPipelineNeedsUpdate('topology');\n }\n }\n\n /**\n * Updates the buffer layout.\n * @note Triggers a pipeline rebuild / pipeline cache fetch\n */\n setBufferLayout(bufferLayout: BufferLayout[]): void {\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n const nextBufferLayout = this._gpuGeometry\n ? bufferLayoutHelper.mergeBufferLayouts(bufferLayout, this._gpuGeometry.bufferLayout)\n : bufferLayout;\n if (deepEqual(nextBufferLayout, this.bufferLayout, -1)) {\n return;\n }\n\n this.bufferLayout = nextBufferLayout;\n this._setPipelineNeedsUpdate('bufferLayout');\n\n // Recreate the pipeline\n this.pipeline = this._updatePipeline();\n\n // vertex array needs to be updated if we update buffer layout,\n // but not if we update parameters\n this.vertexArray = this.device.createVertexArray({\n shaderLayout: this.pipeline.shaderLayout,\n bufferLayout: this.pipeline.bufferLayout\n });\n\n // Reapply geometry attributes to the new vertex array\n if (this._gpuGeometry) {\n this._setGeometryAttributes(this._gpuGeometry);\n }\n }\n\n /**\n * Set GPU parameters.\n * @note Can trigger a pipeline rebuild / pipeline cache fetch.\n * @param parameters\n */\n setParameters(parameters: RenderPipelineParameters) {\n if (!deepEqual(parameters, this.parameters, 2)) {\n this.parameters = parameters;\n this._setPipelineNeedsUpdate('parameters');\n }\n }\n\n // Update dynamic fields\n\n /**\n * Updates the instance count (used in draw calls)\n * @note Any attributes with stepMode=instance need to be at least this big\n */\n setInstanceCount(instanceCount: number): void {\n this.instanceCount = instanceCount;\n // luma.gl examples don't set props.isInstanced and rely on auto-detection\n // but deck.gl sets instanceCount even for models that are not instanced.\n if (this.isInstanced === undefined && instanceCount > 0) {\n this.isInstanced = true;\n }\n this.setNeedsRedraw('instanceCount');\n }\n\n /**\n * Updates the vertex count (used in draw calls)\n * @note Any attributes with stepMode=vertex need to be at least this big\n */\n setVertexCount(vertexCount: number): void {\n this.vertexCount = vertexCount;\n this.setNeedsRedraw('vertexCount');\n }\n\n /** Updates the indexed draw count override. */\n setIndexCount(indexCount: number | undefined): void {\n this.indexCount = indexCount;\n this.setNeedsRedraw('indexCount');\n }\n\n /** Updates the first indexed/non-indexed draw offsets. */\n setDrawOffsets({firstVertex, firstIndex}: {firstVertex: number; firstIndex: number}): void {\n this.firstVertex = firstVertex;\n this.firstIndex = firstIndex;\n this.setNeedsRedraw('drawOffsets');\n }\n\n /** Set the shader inputs */\n setShaderInputs(shaderInputs: ShaderInputs): void {\n this.shaderInputs = shaderInputs;\n this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules);\n // Create uniform buffer bindings for all modules that actually have uniforms\n for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) {\n if (shaderModuleHasUniforms(module) && !this.material?.ownsModule(moduleName)) {\n const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName);\n this.bindings[`${moduleName}Uniforms`] = uniformBuffer;\n }\n }\n this.setNeedsRedraw('shaderInputs');\n }\n\n setMaterial(material: Material | null): void {\n this.material = material;\n this.setNeedsRedraw('material');\n }\n\n /** Update uniform buffers from the model's shader inputs */\n /**\n * Flushes current shader-input values into managed uniform buffers and\n * non-material bindings.\n *\n * @param commandEncoder - Optional encoder used to order uniform uploads with\n * subsequent draw commands.\n */\n updateShaderInputs(commandEncoder?: CommandEncoder): void {\n this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(), commandEncoder);\n this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues()));\n // TODO - this is already tracked through buffer/texture update times?\n this.setNeedsRedraw('shaderInputs');\n }\n\n /**\n * Sets bindings (textures, samplers, uniform buffers)\n */\n setBindings(bindings: Record<string, ModelBinding>): void {\n Object.assign(this.bindings, bindings);\n this.setNeedsRedraw('bindings');\n }\n\n /**\n * Updates optional transform feedback. WebGL only.\n */\n setTransformFeedback(transformFeedback: TransformFeedback | null): void {\n this.transformFeedback = transformFeedback;\n this.setNeedsRedraw('transformFeedback');\n }\n\n /**\n * Sets the index buffer\n * @todo - how to unset it if we change geometry?\n */\n setIndexBuffer(indexBuffer: ModelBuffer | null): void {\n const resolvedIndexBuffer =\n indexBuffer instanceof DynamicBuffer ? indexBuffer.buffer : indexBuffer;\n this.indexBuffer = resolvedIndexBuffer;\n this._dynamicIndexBufferSource =\n indexBuffer instanceof DynamicBuffer\n ? {source: indexBuffer, generation: indexBuffer.generation}\n : null;\n this.vertexArray.setIndexBuffer(resolvedIndexBuffer);\n this.setNeedsRedraw('indexBuffer');\n }\n\n /**\n * Sets attributes (buffers)\n * @note Overrides any attributes previously set with the same name\n */\n setAttributes(buffers: Record<string, ModelBuffer>, options?: {disableWarnings?: boolean}): void {\n this._drawBlockedReason = false;\n const disableWarnings = options?.disableWarnings ?? this.props.disableWarnings;\n if (buffers['indices']) {\n log.warn(\n `Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`\n )();\n }\n\n // ensure bufferLayout order matches source layout so we bind\n // the correct buffers to the correct indices in webgpu.\n this.bufferLayout = sortedBufferLayoutByShaderSourceLocations(\n this.pipeline.shaderLayout,\n this.bufferLayout\n );\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n\n // Check if all buffers have a layout\n for (const [bufferName, buffer] of Object.entries(buffers)) {\n const resolvedBuffer = buffer instanceof DynamicBuffer ? buffer.buffer : buffer;\n const bufferLayout = bufferLayoutHelper.getBufferLayout(bufferName);\n if (!bufferLayout) {\n if (!disableWarnings) {\n log.warn(`Model(${this.id}): Missing layout for buffer \"${bufferName}\".`)();\n }\n continue; // eslint-disable-line no-continue\n }\n\n // In WebGL, for an interleaved attribute we may need to set multiple attributes\n // but in WebGPU, we set it according to the buffer's position in the vertexArray\n const attributeNames = bufferLayoutHelper.getAttributeNamesForBuffer(bufferLayout);\n let set = false;\n for (const attributeName of attributeNames) {\n const attributeInfo = this._attributeInfos[attributeName];\n if (attributeInfo) {\n const bufferSlot =\n this.device.type === 'webgpu'\n ? this.vertexArray.getBufferSlot(attributeInfo.bufferName)\n : attributeInfo.location;\n if (bufferSlot === null) {\n if (!disableWarnings) {\n log.warn(\n `Model(${this.id}): Missing vertex array slot for buffer \"${attributeInfo.bufferName}\".`\n )();\n }\n continue; // eslint-disable-line no-continue\n }\n\n this.vertexArray.setBuffer(bufferSlot, resolvedBuffer);\n if (buffer instanceof DynamicBuffer) {\n this._dynamicAttributeBufferSources[bufferSlot] = {\n source: buffer,\n generation: buffer.generation\n };\n } else {\n delete this._dynamicAttributeBufferSources[bufferSlot];\n }\n set = true;\n }\n }\n if (!set && !disableWarnings) {\n log.warn(\n `Model(${this.id}): Ignoring buffer \"${resolvedBuffer.id}\" for unknown attribute \"${bufferName}\"`\n )();\n }\n }\n this.setNeedsRedraw('attributes');\n }\n\n /**\n * Sets constant attributes\n * @note Overrides any attributes previously set with the same name\n * Constant attributes are only supported in WebGL, not in WebGPU\n * Any attribute that is disabled in the current vertex array object\n * is read from the context's global constant value for that attribute location.\n * @param constantAttributes\n */\n setConstantAttributes(\n attributes: Record<string, TypedArray>,\n options?: {disableWarnings?: boolean}\n ): void {\n for (const [attributeName, value] of Object.entries(attributes)) {\n const attributeInfo = this._attributeInfos[attributeName];\n if (attributeInfo) {\n this.vertexArray.setConstantWebGL(attributeInfo.location, value);\n } else if (!(options?.disableWarnings ?? this.props.disableWarnings)) {\n log.warn(\n `Model \"${this.id}: Ignoring constant supplied for unknown attribute \"${attributeName}\"`\n )();\n }\n }\n this.setNeedsRedraw('constants');\n }\n\n // INTERNAL METHODS\n\n /** Check that bindings are loaded. Returns id of first binding that is still loading. */\n _areBindingsLoading(): string | false {\n for (const binding of Object.values(this.bindings)) {\n if (isTextureBindingSource(binding) && !binding.isReady) {\n return binding.id;\n }\n }\n for (const binding of Object.values(this.material?.bindings || {})) {\n if (isTextureBindingSource(binding) && !binding.isReady) {\n return binding.id;\n }\n }\n return false;\n }\n\n /**\n * Resolves ready model bindings for the current shader layout.\n * @param shaderLayout Reflected bindings used to select copied or external texture resolution.\n */\n _getBindings(\n shaderLayout: AnyShaderLayout = this._getCurrentShaderLayout()\n ): Record<string, Binding> {\n const validBindings: Record<string, Binding> = {};\n\n for (const [name, binding] of Object.entries(this.bindings)) {\n const resolvedBinding = resolveModelBinding(name, binding, shaderLayout);\n if (resolvedBinding) {\n validBindings[name] = resolvedBinding;\n }\n }\n\n return validBindings;\n }\n\n /**\n * Groups resolved model and material bindings for the current shader layout.\n * @param shaderLayout Reflected bindings used to group logical binding names.\n * @param bindings Model bindings already resolved for this draw preparation.\n */\n _getBindGroups(\n shaderLayout: AnyShaderLayout = this._getCurrentShaderLayout(),\n bindings: Record<string, Binding> = this._getBindings(shaderLayout)\n ): BindingsByGroup {\n const bindGroups = shaderLayout.bindings.length\n ? normalizeBindingsByGroup(shaderLayout, bindings)\n : {0: bindings};\n\n if (!this.material) {\n return bindGroups;\n }\n\n for (const [groupKey, groupBindings] of Object.entries(\n this.material.getBindingsByGroup(shaderLayout)\n )) {\n const group = Number(groupKey);\n bindGroups[group] = {\n ...(bindGroups[group] || {}),\n ...groupBindings\n };\n }\n\n return bindGroups;\n }\n\n _getBindGroupCacheKeys(): Partial<Record<number, object>> {\n const bindGroupCacheKey = this.material?.getBindGroupCacheKey(3);\n return bindGroupCacheKey ? {3: bindGroupCacheKey} : {};\n }\n\n /** Get the timestamp of the latest updated bound GPU memory resource (buffer/texture). */\n _getBindingsUpdateTimestamp(): number {\n let timestamp = 0;\n if (this._dynamicIndexBufferSource) {\n timestamp = Math.max(timestamp, this._dynamicIndexBufferSource.source.updateTimestamp);\n }\n for (const entry of Object.values(this._dynamicAttributeBufferSources)) {\n timestamp = Math.max(timestamp, entry.source.updateTimestamp);\n }\n for (const binding of Object.values(this.bindings)) {\n if (binding instanceof TextureView) {\n timestamp = Math.max(timestamp, binding.texture.updateTimestamp);\n } else if (\n binding instanceof Buffer ||\n binding instanceof Texture ||\n binding instanceof ExternalTexture\n ) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (binding instanceof DynamicBuffer) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (isTextureBindingSource(binding)) {\n timestamp = binding.isReady\n ? Math.max(timestamp, binding.updateTimestamp)\n : // The texture will become available in the future\n Infinity;\n } else if (isBufferRangeBinding(binding)) {\n timestamp = Math.max(\n timestamp,\n binding.buffer instanceof DynamicBuffer\n ? binding.buffer.updateTimestamp\n : binding.buffer.updateTimestamp\n );\n }\n }\n return Math.max(timestamp, this.material?.getBindingsUpdateTimestamp() || 0);\n }\n\n /**\n * Updates the optional geometry attributes\n * Geometry, sets several attributes, indexBuffer, and also vertex count\n * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n _setGeometryAttributes(gpuGeometry: GPUGeometry): void {\n // Filter geometry attribute so that we don't issue warnings for unused attributes\n const attributes = {...gpuGeometry.attributes};\n for (const [attributeName] of Object.entries(attributes)) {\n if (\n !this.pipeline.shaderLayout.attributes.find(layout => layout.name === attributeName) &&\n attributeName !== 'positions'\n ) {\n delete attributes[attributeName];\n }\n }\n\n // TODO - delete previous geometry?\n this.vertexCount = gpuGeometry.vertexCount;\n this.setIndexBuffer(gpuGeometry.indices || null);\n this.setAttributes(gpuGeometry.attributes, {disableWarnings: true});\n this.setAttributes(attributes, {disableWarnings: this.props.disableWarnings});\n\n this.setNeedsRedraw('geometry attributes');\n }\n\n /** Mark pipeline as needing update */\n _setPipelineNeedsUpdate(reason: string): void {\n this._pipelineNeedsUpdate ||= reason;\n this._drawBlockedReason = false;\n this.setNeedsRedraw(reason);\n }\n\n /** Update pipeline if needed */\n _updatePipeline(): RenderPipeline {\n if (this._pipelineNeedsUpdate) {\n let prevShaderVs: Shader | null = null;\n let prevShaderFs: Shader | null = null;\n if (this.pipeline) {\n log.log(\n 1,\n `Model ${this.id}: Recreating pipeline because \"${this._pipelineNeedsUpdate}\".`\n )();\n prevShaderVs = this.pipeline.vs;\n prevShaderFs = this.pipeline.fs;\n }\n\n this._pipelineNeedsUpdate = false;\n\n const vs = this.shaderFactory.createShader({\n id: `${this.id}-vertex`,\n stage: 'vertex',\n source: this.source || this.vs,\n debugShaders: this.props.debugShaders\n });\n\n let fs: Shader | null = null;\n if (this.source) {\n fs = vs;\n } else if (this.fs) {\n fs = this.shaderFactory.createShader({\n id: `${this.id}-fragment`,\n stage: 'fragment',\n source: this.source || this.fs,\n debugShaders: this.props.debugShaders\n });\n }\n\n this.pipeline = this.pipelineFactory.createRenderPipeline({\n ...this.props,\n bindings: undefined,\n bufferLayout: this.bufferLayout,\n colorAttachmentFormats: this._colorAttachmentFormats,\n depthStencilAttachmentFormat: this._depthStencilAttachmentFormat,\n topology: this.topology,\n parameters: this.parameters,\n bindGroups: undefined,\n vs,\n fs\n });\n\n this._attributeInfos = getAttributeInfosFromLayouts(\n this.pipeline.shaderLayout,\n this.bufferLayout\n );\n\n if (prevShaderVs) this.shaderFactory.release(prevShaderVs);\n if (prevShaderFs && prevShaderFs !== prevShaderVs) {\n this.shaderFactory.release(prevShaderFs);\n }\n }\n return this.pipeline;\n }\n\n /** Throttle draw call logging */\n _lastLogTime = 0;\n _logOpen = false;\n\n _logDrawCallStart(): void {\n // IF level is 4 or higher, log every frame.\n const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;\n if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {\n return;\n }\n\n this._lastLogTime = Date.now();\n this._logOpen = true;\n\n log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {collapsed: log.level <= 2})();\n }\n\n _logDrawCallEnd(): void {\n if (this._logOpen) {\n const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.shaderLayout, this.id);\n\n // log.table(logLevel, attributeTable)();\n // log.table(logLevel, uniformTable)();\n log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();\n\n const uniformTable = this.shaderInputs.getDebugTable();\n log.table(LOG_DRAW_PRIORITY, uniformTable)();\n\n const attributeTable = this._getAttributeDebugTable();\n log.table(LOG_DRAW_PRIORITY, this._attributeInfos)();\n log.table(LOG_DRAW_PRIORITY, attributeTable)();\n\n log.groupEnd(LOG_DRAW_PRIORITY)();\n this._logOpen = false;\n }\n }\n\n protected _drawCount = 0;\n _logFramebuffer(renderPass: RenderPass): void {\n const debugFramebuffers = this.device.props.debugFramebuffers;\n this._drawCount++;\n // Update first 3 frames and then every 60 frames\n if (!debugFramebuffers) {\n // } || (this._drawCount++ > 3 && this._drawCount % 60)) {\n return;\n }\n const framebuffer = renderPass.props.framebuffer;\n debugFramebuffer(renderPass, framebuffer, {\n id: framebuffer?.id || `${this.id}-framebuffer`,\n minimap: true\n });\n }\n\n _getAttributeDebugTable(): Record<string, Record<string, unknown>> {\n const table: Record<string, Record<string, unknown>> = {};\n for (const [name, attributeInfo] of Object.entries(this._attributeInfos)) {\n const values = this.vertexArray.attributes[attributeInfo.location];\n table[attributeInfo.location] = {\n name,\n type: attributeInfo.shaderType,\n values: values\n ? this._getBufferOrConstantValues(values, attributeInfo.bufferDataType)\n : 'null'\n };\n }\n if (this.vertexArray.indexBuffer) {\n const {indexBuffer} = this.vertexArray;\n const values =\n indexBuffer.indexType === 'uint32'\n ? new Uint32Array(indexBuffer.debugData)\n : new Uint16Array(indexBuffer.debugData);\n table['indices'] = {\n name: 'indices',\n type: indexBuffer.indexType,\n values: values.toString()\n };\n }\n return table;\n }\n\n // TODO - fix typing of luma data types\n _getBufferOrConstantValues(attribute: Buffer | TypedArray, dataType: any): string {\n const TypedArrayConstructor = dataTypeDecoder.getTypedArrayConstructor(dataType);\n const typedArray =\n attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;\n return typedArray.toString();\n }\n\n private _getNonMaterialBindings(\n bindings: Record<string, ModelBinding>\n ): Record<string, ModelBinding> {\n if (!this.material) {\n return bindings;\n }\n\n const filteredBindings: Record<string, ModelBinding> = {};\n for (const [name, binding] of Object.entries(bindings)) {\n if (!this.material.ownsBinding(name)) {\n filteredBindings[name] = binding;\n }\n }\n return filteredBindings;\n }\n\n /** Returns the current reflected shader layout or the pre-reflection empty layout. */\n private _getCurrentShaderLayout(): AnyShaderLayout {\n return this.pipeline?.shaderLayout || this.props.shaderLayout || {bindings: []};\n }\n\n private _syncDynamicBuffers(): void {\n if (\n this._dynamicIndexBufferSource &&\n this._dynamicIndexBufferSource.generation !== this._dynamicIndexBufferSource.source.generation\n ) {\n const resolvedIndexBuffer = this._dynamicIndexBufferSource.source.buffer;\n this.indexBuffer = resolvedIndexBuffer;\n this.vertexArray.setIndexBuffer(resolvedIndexBuffer);\n this._dynamicIndexBufferSource.generation = this._dynamicIndexBufferSource.source.generation;\n this.setNeedsRedraw('dynamic index buffer');\n }\n\n for (const [locationKey, entry] of Object.entries(this._dynamicAttributeBufferSources)) {\n if (entry.generation !== entry.source.generation) {\n this.vertexArray.setBuffer(Number(locationKey), entry.source.buffer);\n entry.generation = entry.source.generation;\n this.setNeedsRedraw('dynamic attribute buffer');\n }\n }\n }\n private _syncAttachmentFormats(renderPass: RenderPass): void {\n if (this.device.type !== 'webgpu') {\n return;\n }\n\n const framebuffer =\n (\n renderPass as RenderPass & {\n framebuffer?: {\n colorAttachments?: Array<{texture?: {format?: TextureFormatColor}} | null>;\n depthStencilAttachment?: {texture?: {format?: TextureFormatDepthStencil}} | null;\n };\n }\n ).framebuffer || renderPass.props.framebuffer;\n const renderBundleProps = renderPass.props as RenderPass['props'] & {\n colorAttachmentFormats?: (TextureFormatColor | null)[];\n depthStencilAttachmentFormat?: TextureFormatDepthStencil | false;\n };\n\n const nextColorAttachmentFormats =\n renderBundleProps.colorAttachmentFormats ??\n framebuffer?.colorAttachments?.map(colorAttachment =>\n asColorAttachmentFormat(colorAttachment?.texture?.format)\n );\n const nextDepthStencilAttachmentFormat =\n renderBundleProps.depthStencilAttachmentFormat === false\n ? undefined\n : (renderBundleProps.depthStencilAttachmentFormat ??\n asDepthStencilAttachmentFormat(framebuffer?.depthStencilAttachment?.texture?.format));\n\n if (\n !deepEqual(this._colorAttachmentFormats, nextColorAttachmentFormats, 1) ||\n this._depthStencilAttachmentFormat !== nextDepthStencilAttachmentFormat\n ) {\n this._colorAttachmentFormats = nextColorAttachmentFormats;\n this._depthStencilAttachmentFormat = nextDepthStencilAttachmentFormat;\n this._setPipelineNeedsUpdate('attachment formats');\n }\n }\n}\n\n// HELPERS\n\nfunction normalizeShaderPluginAttributeNames(\n shaderLayout: ShaderLayout | null | undefined,\n vertexInputs: Record<string, AttributeShaderType>\n): ShaderLayout | null | undefined {\n if (!shaderLayout || Object.keys(vertexInputs).length === 0) {\n return shaderLayout;\n }\n\n return {\n ...shaderLayout,\n attributes: shaderLayout.attributes.map(attribute => {\n const publicName = attribute.name.startsWith('_luma_')\n ? attribute.name.slice('_luma_'.length)\n : null;\n return publicName && vertexInputs[publicName] ? {...attribute, name: publicName} : attribute;\n })\n };\n}\n\n/**\n * Resolves one model binding against the current shader layout.\n * @param bindingName Logical model binding name.\n * @param binding Model binding or deferred engine binding source.\n * @param shaderLayout Reflected bindings used to select copied or external texture resolution.\n * @returns Concrete core binding, or `null` while a deferred source is unavailable.\n */\nfunction resolveModelBinding(\n bindingName: string,\n binding: ModelBinding,\n shaderLayout: AnyShaderLayout\n): Binding | null {\n if (isTextureBindingSource(binding)) {\n const bindingLayout = getTextureBindingLayout(shaderLayout, bindingName, {\n fallbackGroup: 0\n });\n return bindingLayout ? binding.resolveTextureBinding(bindingLayout) : null;\n }\n\n if (binding instanceof DynamicBuffer) {\n return binding.buffer;\n }\n\n if (isBufferRangeBinding(binding)) {\n return resolveBufferRangeBinding(binding);\n }\n\n return binding;\n}\nfunction asColorAttachmentFormat(format?: string | null): TextureFormatColor | null {\n return format && !isDepthStencilAttachmentFormat(format) ? (format as TextureFormatColor) : null;\n}\n\nfunction asDepthStencilAttachmentFormat(\n format?: string | null\n): TextureFormatDepthStencil | undefined {\n return format && isDepthStencilAttachmentFormat(format) ? format : undefined;\n}\n\nfunction isDepthStencilAttachmentFormat(format: string): format is TextureFormatDepthStencil {\n return DEPTH_STENCIL_ATTACHMENT_FORMATS.includes(format as TextureFormatDepthStencil);\n}\n\n/** Create a shadertools platform info from the Device */\nexport function getPlatformInfo(device: Device): PlatformInfo {\n return {\n type: device.type,\n shaderLanguage: device.info.shadingLanguage,\n shaderLanguageVersion: device.info.shadingLanguageVersion as 100 | 300,\n gpu: device.info.gpu,\n limits: device.limits as unknown as Record<string, number | undefined>,\n // HACK - we pretend that the DeviceFeatures is a Set, it has a similar API\n features: device.features as unknown as Set<DeviceFeature>\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PrimitiveTopology, BufferLayout} from '@luma.gl/core';\nimport {Device, Buffer} from '@luma.gl/core';\nimport {type Geometry, getGeometryShaderAttributeName} from '../geometry/geometry';\nimport {makeInterleavedGeometry} from './geometry-utils';\nimport {uid} from '../utils/uid';\n\n/** Properties used to create a {@link GPUGeometry}. */\nexport type GPUGeometryProps = {\n /** Application-provided identifier. */\n id?: string;\n\n /** Determines how vertices are assembled into primitives. */\n topology: 'point-list' | 'line-list' | 'line-strip' | 'triangle-list' | 'triangle-strip';\n\n /** Draw vertex count. */\n vertexCount: number;\n\n /** Buffer layout matching the supplied GPU vertex buffers. */\n bufferLayout: BufferLayout[];\n\n /** Optional GPU index buffer. */\n indices?: Buffer | null;\n\n /** GPU vertex buffers, keyed by buffer layout name. */\n attributes: Record<string, Buffer>;\n};\n\n/**\n * GPU-backed geometry container.\n *\n * `GPUGeometry` owns already-created vertex and index buffers plus the `bufferLayout` metadata\n * needed to bind those buffers to shader attributes.\n */\nexport class GPUGeometry {\n /** Application-provided or generated identifier. */\n readonly id: string;\n\n /** Application-owned metadata. */\n userData: Record<string, unknown> = {};\n\n /** Determines how vertices are assembled into primitives. */\n readonly topology?: PrimitiveTopology;\n\n /** Buffer layout matching {@link GPUGeometry.attributes}. */\n readonly bufferLayout: BufferLayout[] = [];\n\n /** Resolved draw vertex count. */\n readonly vertexCount: number;\n\n /** Optional GPU index buffer. */\n readonly indices?: Buffer | null;\n\n /** GPU vertex buffers, keyed by buffer layout name. */\n readonly attributes: Record<string, Buffer>;\n\n /** Creates GPU-backed geometry from existing buffers. */\n constructor(props: GPUGeometryProps) {\n this.id = props.id || uid('geometry');\n this.topology = props.topology;\n this.indices = props.indices || null;\n this.attributes = props.attributes;\n\n this.vertexCount = props.vertexCount;\n\n this.bufferLayout = props.bufferLayout || [];\n\n if (this.indices) {\n if (!(this.indices.usage & Buffer.INDEX)) {\n throw new Error('Index buffer must have INDEX usage');\n }\n }\n }\n\n /** Destroys the owned index and vertex buffers. */\n destroy(): void {\n this.indices?.destroy();\n for (const attribute of Object.values(this.attributes)) {\n attribute.destroy();\n }\n }\n\n /** Returns the draw vertex count. */\n getVertexCount(): number {\n return this.vertexCount;\n }\n\n /** Returns the GPU vertex buffers. */\n getAttributes(): Record<string, Buffer> {\n return this.attributes;\n }\n\n /** Returns the GPU index buffer, or `null` for non-indexed geometry. */\n getIndexes(): Buffer | null {\n return this.indices || null;\n }\n\n _calculateVertexCount(positions: Buffer): number {\n // Assume that positions is a fully packed float32x3 buffer\n const vertexCount = positions.byteLength / 12;\n return vertexCount;\n }\n}\n\n/**\n * Converts CPU geometry into GPU geometry.\n *\n * CPU `Geometry` input is interleaved before upload so the resulting `GPUGeometry` has one vertex\n * buffer plus an optional index buffer. Passing a `GPUGeometry` returns the original instance.\n */\nexport function makeGPUGeometry(device: Device, geometry: Geometry | GPUGeometry): GPUGeometry {\n if (geometry instanceof GPUGeometry) {\n return geometry;\n }\n\n const sourceGeometry = makeInterleavedGeometry(geometry);\n const indices = getIndexBufferFromGeometry(device, sourceGeometry);\n const {attributes, bufferLayout} = getAttributeBuffersFromGeometry(device, sourceGeometry);\n return new GPUGeometry({\n topology: sourceGeometry.topology || 'triangle-list',\n bufferLayout,\n vertexCount: sourceGeometry.vertexCount,\n indices,\n attributes\n });\n}\n\n/** Creates a GPU index buffer from CPU geometry index data, when present. */\nexport function getIndexBufferFromGeometry(device: Device, geometry: Geometry): Buffer | undefined {\n if (!geometry.indices) {\n return undefined;\n }\n const data = geometry.indices.value;\n return device.createBuffer({usage: Buffer.INDEX, data});\n}\n\n/**\n * Uploads one GPU vertex buffer for each CPU geometry attribute key and preserves its buffer\n * layout metadata.\n */\nexport function getAttributeBuffersFromGeometry(\n device: Device,\n geometry: Geometry\n): {attributes: Record<string, Buffer>; bufferLayout: BufferLayout[]; vertexCount: number} {\n const attributes: Record<string, Buffer> = {};\n for (const [attributeName, attribute] of Object.entries(geometry.attributes)) {\n const name =\n geometry.bufferLayout.find(bufferLayout => bufferLayout.name === attributeName)?.name ||\n getGeometryShaderAttributeName(attributeName);\n if (attribute) {\n attributes[name] = device.createBuffer({\n data: attribute.value,\n id: `${attributeName}-buffer`\n });\n }\n }\n\n return {\n attributes,\n bufferLayout: geometry.bufferLayout,\n vertexCount: geometry.vertexCount\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '@math.gl/core';\nimport type {BufferLayout, PrimitiveTopology} from '@luma.gl/core';\nimport {vertexFormatDecoder} from '@luma.gl/core';\nimport {uid} from '../utils/uid';\n\n/** CPU-side attribute data accepted by {@link Geometry}. */\nexport type GeometryAttributeInput = GeometryAttribute | TypedArray;\n\n/** Properties used to create a {@link Geometry}. */\nexport type GeometryProps = {\n /** Application-provided identifier. */\n id?: string;\n /** Determines how vertices are assembled into primitives. */\n topology: 'point-list' | 'line-list' | 'line-strip' | 'triangle-list' | 'triangle-strip';\n /** Draw vertex count. Auto-calculated from attributes or indices when omitted. */\n vertexCount?: number;\n /** CPU attributes, keyed by caller-provided names such as glTF mesh attribute semantics. */\n attributes: Record<string, GeometryAttributeInput>;\n /**\n * Maps geometry buffers to shader attributes.\n *\n * If omitted, the constructor creates one shader-facing buffer layout entry for each attribute.\n * Explicit buffer layouts are preserved unchanged.\n */\n bufferLayout?: BufferLayout[];\n /** Optional index data. Indices are always stored separately from vertex attributes. */\n indices?: GeometryAttribute | TypedArray;\n};\n\n/** Attributes returned by {@link Geometry.getAttributes}. */\nexport type GeometryAttributes = Record<string, GeometryAttribute | undefined> & {\n /** Optional index attribute, included when the geometry is indexed. */\n indices?: GeometryAttribute & {size: 1; value: Uint32Array | Uint16Array};\n};\n\n/** Typed-array backed CPU geometry attribute. */\nexport type GeometryAttribute = {\n /** Number of typed-array elements per vertex. */\n size?: number;\n /** Attribute data. */\n value: TypedArray;\n /** Additional attribute metadata consumed by geometry utilities. */\n [key: string]: any;\n};\n\n/**\n * CPU-side geometry container.\n *\n * `Geometry` stores typed-array vertex data, optional index data, and an always-populated\n * `bufferLayout` that describes how its attributes map to shader inputs. CPU attribute names are\n * preserved as supplied; synthesized buffer layouts map supported glTF-style names such as\n * `POSITION` and `TEXCOORD_0` to default shader names such as `positions` and `texCoords`.\n */\nexport class Geometry {\n /** Application-provided or generated identifier. */\n readonly id: string;\n\n /** Determines how vertices are assembled into primitives. */\n readonly topology?: PrimitiveTopology;\n\n /** Resolved draw vertex count. */\n readonly vertexCount: number;\n\n /** Optional index attribute. */\n readonly indices?: GeometryAttribute;\n\n /** CPU attributes, keyed by caller-provided source attribute name. */\n readonly attributes: Record<string, GeometryAttribute | undefined>;\n\n /** Buffer layout matching the geometry attributes. Always populated. */\n readonly bufferLayout: BufferLayout[];\n\n /** Application-owned metadata. */\n userData: Record<string, unknown> = {};\n\n /** Creates a CPU geometry and wraps raw typed arrays into attribute records. */\n constructor(props: GeometryProps) {\n const {attributes = {}, indices = null, vertexCount = null} = props;\n\n this.id = props.id || uid('geometry');\n this.topology = props.topology;\n\n if (indices) {\n this.indices = ArrayBuffer.isView(indices) ? {value: indices, size: 1} : indices;\n }\n\n this.attributes = {};\n\n for (const [attributeName, attributeValue] of Object.entries(attributes)) {\n // Wrap \"unwrapped\" arrays and try to autodetect their type\n const attribute: GeometryAttribute = ArrayBuffer.isView(attributeValue)\n ? {value: attributeValue}\n : attributeValue;\n\n if (!ArrayBuffer.isView(attribute.value)) {\n throw new Error(\n `${this._print(attributeName)}: must be typed array or object with value as typed array`\n );\n }\n\n if ((attributeName === 'POSITION' || attributeName === 'positions') && !attribute.size) {\n attribute.size = 3;\n }\n\n // Move indices to separate field\n if (attributeName === 'indices') {\n if (this.indices) {\n throw new Error('Multiple indices detected');\n }\n this.indices = attribute;\n } else {\n const shaderAttributeName = getGeometryShaderAttributeName(attributeName);\n const storedAttributeName = Object.keys(this.attributes).find(\n name => getGeometryShaderAttributeName(name) === shaderAttributeName\n );\n if (storedAttributeName) {\n delete this.attributes[storedAttributeName];\n }\n this.attributes[attributeName] = attribute;\n }\n }\n\n if (this.indices && this.indices['isIndexed'] !== undefined) {\n this.indices = Object.assign({}, this.indices);\n delete this.indices['isIndexed'];\n }\n\n this.vertexCount = vertexCount || this._calculateVertexCount(this.attributes, this.indices);\n this.bufferLayout =\n props.bufferLayout || getBufferLayoutFromGeometryAttributes(this.attributes);\n }\n\n /** Returns the resolved draw vertex count. */\n getVertexCount(): number {\n return this.vertexCount;\n }\n\n /** Returns all attributes, including `indices` when index data is present. */\n getAttributes(): GeometryAttributes {\n return (\n this.indices ? {indices: this.indices, ...this.attributes} : this.attributes\n ) as GeometryAttributes;\n }\n\n // PRIVATE\n\n _print(attributeName: string): string {\n return `Geometry ${this.id} attribute ${attributeName}`;\n }\n\n _setAttributes(attributes: Record<string, GeometryAttribute>, indices: any): this {\n return this;\n }\n\n _calculateVertexCount(\n attributes: Record<string, GeometryAttribute | undefined>,\n indices?: GeometryAttribute\n ): number {\n if (indices) {\n return indices.value.length;\n }\n let vertexCount = Infinity;\n for (const attribute of Object.values(attributes)) {\n if (!attribute) {\n continue; // eslint-disable-line no-continue\n }\n const {value, size, constant} = attribute;\n if (!constant && value && size !== undefined && size >= 1) {\n vertexCount = Math.min(vertexCount, value.length / size);\n }\n }\n\n // assert(Number.isFinite(vertexCount));\n return vertexCount;\n }\n}\n\n/**\n * Converts supported geometry semantic names to default shader attribute names.\n *\n * Use this only at render-layout boundaries. CPU `Geometry.attributes` preserves source names.\n * Names that do not have a built-in mapping are returned unchanged.\n */\nexport function getGeometryShaderAttributeName(attributeName: string): string {\n switch (attributeName) {\n case 'POSITION':\n return 'positions';\n case 'NORMAL':\n return 'normals';\n case 'TEXCOORD_0':\n return 'texCoords';\n case 'TEXCOORD_1':\n return 'texCoords1';\n case 'COLOR_0':\n return 'colors';\n default:\n return attributeName;\n }\n}\n\nfunction getBufferLayoutFromGeometryAttributes(\n attributes: Record<string, GeometryAttribute | undefined>\n): BufferLayout[] {\n const bufferLayout: BufferLayout[] = [];\n for (const [attributeName, attribute] of Object.entries(attributes)) {\n if (!attribute) {\n continue; // eslint-disable-line no-continue\n }\n const {value, size, normalized} = attribute;\n if (size === undefined) {\n throw new Error(`Attribute ${attributeName} is missing a size`);\n }\n bufferLayout.push({\n name: getGeometryShaderAttributeName(attributeName),\n format: vertexFormatDecoder.getVertexFormatFromAttribute(value, size, normalized)\n });\n }\n return bufferLayout;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record<string, number> = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {VertexFormat} from '@luma.gl/core';\nimport {vertexFormatDecoder} from '@luma.gl/core';\nimport type {TypedArray} from '@math.gl/core';\nimport {Geometry, getGeometryShaderAttributeName, type GeometryAttribute} from './geometry';\n\ntype TypedArrayConstructor = {\n new (length: number): TypedArray;\n new (buffer: ArrayBufferLike): TypedArray;\n readonly BYTES_PER_ELEMENT: number;\n};\n\ntype GeometryLike = {\n indices?: GeometryAttribute;\n attributes: Record<string, GeometryAttribute | undefined>;\n};\n\n/** Options for {@link makeInterleavedGeometry}. */\nexport type MakeInterleavedGeometryOptions = {\n /** Name of the packed geometry buffer. Defaults to `geometry`. */\n bufferName?: string;\n\n /** Attribute names to pack. Defaults to all non-index geometry attributes. */\n attributes?: string[];\n\n /**\n * Minimum byte alignment for each packed attribute and for the final byte stride.\n *\n * Defaults to 4 bytes, matching WebGPU and WebGL vertex-buffer alignment constraints.\n */\n minAttributeAlignment?: number;\n};\n\ntype InterleavedAttribute = {\n sourceName: string;\n attributeName: string;\n value: TypedArray;\n size: number;\n format: VertexFormat;\n byteOffset: number;\n byteLength: number;\n};\n\n/**\n * Expands indexed geometry attributes into non-indexed attributes.\n *\n * The returned object keeps the original attribute keys and replaces each non-constant attribute\n * with data expanded through the index buffer. The `indices` field is intentionally omitted from\n * the returned geometry-like object.\n */\nexport function unpackIndexedGeometry<T extends GeometryLike>(geometry: T): GeometryLike {\n const {indices, attributes} = geometry;\n if (!indices) {\n return geometry;\n }\n\n const vertexCount = indices.value.length;\n const unpackedAttributes: Record<string, GeometryAttribute> = {};\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n if (!attribute) {\n continue; // eslint-disable-line\n }\n const {value, size} = attribute;\n const constant = attribute['constant'];\n if (constant || !size) {\n continue; // eslint-disable-line\n }\n const ArrayType = value.constructor as TypedArrayConstructor;\n const unpackedValue = new ArrayType(vertexCount * size);\n for (let x = 0; x < vertexCount; ++x) {\n const index = indices.value[x];\n for (let i = 0; i < size; i++) {\n unpackedValue[x * size + i] = value[index * size + i];\n }\n }\n unpackedAttributes[attributeName] = {size, value: unpackedValue};\n }\n\n return {\n attributes: Object.assign({}, attributes, unpackedAttributes)\n };\n}\n\n/**\n * Packs a CPU {@link Geometry} into one interleaved vertex buffer.\n *\n * The returned value is a normal `Geometry` whose `attributes` contains one packed typed array,\n * and whose `bufferLayout` maps that packed buffer back to the original shader attributes.\n * Calling this function on an already interleaved geometry with the same `bufferName` is\n * idempotent and returns the original instance.\n */\nexport function makeInterleavedGeometry(\n geometry: Geometry,\n options: MakeInterleavedGeometryOptions = {}\n): Geometry {\n const bufferName = options.bufferName || 'geometry';\n if (isInterleavedGeometry(geometry, bufferName)) {\n return geometry;\n }\n\n const minAttributeAlignment = options.minAttributeAlignment || 4;\n const sourceAttributes = getInterleavedSourceAttributes(geometry, options.attributes);\n const interleavedAttributes: InterleavedAttribute[] = [];\n let byteOffset = 0;\n let attributeVertexCount = Infinity;\n\n for (const [sourceName, attribute] of sourceAttributes) {\n if (!attribute) {\n continue; // eslint-disable-line no-continue\n }\n if (attribute['constant']) {\n throw new Error(`Attribute ${sourceName} is constant`);\n }\n const {value, size, normalized} = attribute;\n if (!ArrayBuffer.isView(value)) {\n throw new Error(`Attribute ${sourceName} is missing typed array data`);\n }\n if (size === undefined) {\n throw new Error(`Attribute ${sourceName} is missing a size`);\n }\n\n const format = vertexFormatDecoder.getVertexFormatFromAttribute(value, size, normalized);\n const vertexFormatInfo = vertexFormatDecoder.getVertexFormatInfo(format);\n\n byteOffset = alignTo(byteOffset, minAttributeAlignment);\n interleavedAttributes.push({\n sourceName,\n attributeName: getGeometryShaderAttributeName(sourceName),\n value,\n size,\n format,\n byteOffset,\n byteLength: vertexFormatInfo.byteLength\n });\n byteOffset += vertexFormatInfo.byteLength;\n const sourceVertexCount = value.length / size;\n if (!Number.isInteger(sourceVertexCount)) {\n throw new Error(`Attribute ${sourceName} length is not divisible by size`);\n }\n attributeVertexCount = Math.min(attributeVertexCount, sourceVertexCount);\n }\n\n if (interleavedAttributes.length === 0 || !Number.isFinite(attributeVertexCount)) {\n throw new Error(`Geometry ${geometry.id} has no interleavable attributes`);\n }\n\n const byteStride = alignTo(byteOffset, minAttributeAlignment);\n const arrayBuffer = new ArrayBuffer(attributeVertexCount * byteStride);\n\n for (const attribute of interleavedAttributes) {\n writeInterleavedAttribute(arrayBuffer, attributeVertexCount, byteStride, attribute);\n }\n\n return new Geometry({\n id: geometry.id,\n topology: geometry.topology || 'triangle-list',\n vertexCount: geometry.vertexCount,\n indices: geometry.indices,\n attributes: {\n [bufferName]: {\n value: new Uint8Array(arrayBuffer),\n size: byteStride,\n byteStride\n }\n },\n bufferLayout: [\n {\n name: bufferName,\n stepMode: 'vertex',\n byteStride,\n attributes: interleavedAttributes.map(attribute => ({\n attribute: attribute.attributeName,\n format: attribute.format,\n byteOffset: attribute.byteOffset\n }))\n }\n ]\n });\n}\n\nfunction isInterleavedGeometry(geometry: Geometry, bufferName: string): boolean {\n if (geometry.bufferLayout.length !== 1) {\n return false;\n }\n\n const bufferLayout = geometry.bufferLayout[0];\n return (\n bufferLayout.name === bufferName &&\n Boolean(bufferLayout.attributes?.length) &&\n Boolean(geometry.attributes[bufferName])\n );\n}\n\nfunction getInterleavedSourceAttributes(\n geometry: Geometry,\n attributeNames?: string[]\n): Array<[string, GeometryAttribute | undefined]> {\n if (attributeNames) {\n return attributeNames.map(attributeName => [attributeName, geometry.attributes[attributeName]]);\n }\n return Object.entries(geometry.attributes);\n}\n\nfunction writeInterleavedAttribute(\n arrayBuffer: ArrayBuffer,\n vertexCount: number,\n byteStride: number,\n attribute: InterleavedAttribute\n): void {\n const ArrayType = attribute.value.constructor as TypedArrayConstructor;\n const bytesPerElement = ArrayType.BYTES_PER_ELEMENT;\n\n if (attribute.byteOffset % bytesPerElement !== 0 || byteStride % bytesPerElement !== 0) {\n throw new Error(`Attribute ${attribute.sourceName} is not aligned to its component type`);\n }\n\n const target = new ArrayType(arrayBuffer) as any;\n const source = attribute.value as any;\n const elementOffset = attribute.byteOffset / bytesPerElement;\n const elementStride = byteStride / bytesPerElement;\n\n for (let vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) {\n const sourceIndex = vertexIndex * attribute.size;\n const targetIndex = vertexIndex * elementStride + elementOffset;\n for (let componentIndex = 0; componentIndex < attribute.size; componentIndex++) {\n target[targetIndex + componentIndex] = source[sourceIndex + componentIndex];\n }\n }\n}\n\nfunction alignTo(byteOffset: number, alignment: number): number {\n return Math.ceil(byteOffset / alignment) * alignment;\n}\n\n// export function calculateVertexNormals(positions: Float32Array): Uint8Array {\n// let normals = new Uint8Array(positions.length / 3);\n\n// for (let i = 0; i < positions.length; i++) {\n// const vec1 = new Vector3(positions.subarray(i * 3, i + 0, i + 3));\n// const vec2 = new Vector3(positions.subarray(i + 3, i + 6));\n// const vec3 = new Vector3(positions.subarray(i + 6, i + 9));\n\n// const normal = new Vector3(vec1).cross(vec2).normalize();\n// normals.set(normal[0], i + 4);\n// normals.set(normal[1], i + 4 + 1);\n// normals.set(normal[2], i + 2);\n// }\n// const normal = new Vector3(vec1).cross(vec2).normalize();\n// }\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderLayout} from '@luma.gl/core';\n\n/**\n * Extracts a table suitable for `console.table()` from a shader layout to assist in debugging.\n * @param layout shader layout\n * @param name app should provide the most meaningful name, usually the model or pipeline name / id.\n * @returns\n */\nexport function getDebugTableForShaderLayout(\n layout: ShaderLayout,\n name: string\n): Record<string, Record<string, string>> {\n const table: Record<string, Record<string, string>> = {};\n\n const header = 'Values'; // '`Shader Layout for ${name}`;\n\n if (layout.attributes.length === 0 && !layout.varyings?.length) {\n return {'No attributes or varyings': {[header]: 'N/A'}};\n }\n\n for (const attributeDeclaration of layout.attributes) {\n if (attributeDeclaration) {\n const glslDeclaration = `${attributeDeclaration.location} ${attributeDeclaration.name}: ${attributeDeclaration.type}`;\n table[`in ${glslDeclaration}`] = {[header]: attributeDeclaration.stepMode || 'vertex'};\n }\n }\n\n for (const varyingDeclaration of layout.varyings || []) {\n const glslDeclaration = `${varyingDeclaration.location} ${varyingDeclaration.name}`;\n table[`out ${glslDeclaration}`] = {[header]: JSON.stringify(varyingDeclaration)};\n }\n\n return table;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, Framebuffer, RenderPass, Texture} from '@luma.gl/core';\n\nconst DEBUG_FRAMEBUFFER_STATE_KEY = '__debugFramebufferState';\nconst DEFAULT_MARGIN_PX = 8;\n\ntype DebugFramebufferOptions = {\n id: string;\n minimap?: boolean;\n opaque?: boolean;\n top?: string;\n left?: string;\n rgbaScale?: number;\n};\n\ntype DebugFramebufferState = {\n flushing: boolean;\n queuedFramebuffers: Framebuffer[];\n};\n\n/**\n * Debug utility to blit queued offscreen framebuffers into the default framebuffer\n * without CPU readback. Currently implemented for WebGL only.\n */\nexport function debugFramebuffer(\n renderPass: RenderPass,\n source: Framebuffer | Texture | null,\n options: DebugFramebufferOptions\n): void {\n if (renderPass.device.type !== 'webgl') {\n return;\n }\n\n const state = getDebugFramebufferState(renderPass.device);\n if (state.flushing) {\n return;\n }\n\n if (isDefaultRenderPass(renderPass)) {\n flushDebugFramebuffers(renderPass, options, state);\n return;\n }\n\n if (source && isFramebuffer(source) && source.handle !== null) {\n if (!state.queuedFramebuffers.includes(source)) {\n state.queuedFramebuffers.push(source);\n }\n }\n}\n\nfunction flushDebugFramebuffers(\n renderPass: RenderPass,\n options: DebugFramebufferOptions,\n state: DebugFramebufferState\n): void {\n if (state.queuedFramebuffers.length === 0) {\n return;\n }\n\n const webglDevice = renderPass.device as Device & {gl: WebGL2RenderingContext};\n const {gl} = webglDevice;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n const [targetWidth, targetHeight] = renderPass.device\n .getDefaultCanvasContext()\n .getDrawingBufferSize();\n\n let topPx = parseCssPixel(options.top, DEFAULT_MARGIN_PX);\n const leftPx = parseCssPixel(options.left, DEFAULT_MARGIN_PX);\n\n state.flushing = true;\n try {\n for (const framebuffer of state.queuedFramebuffers) {\n const [targetX0, targetY0, targetX1, targetY1, previewHeight] = getOverlayRect({\n framebuffer,\n targetWidth,\n targetHeight,\n topPx,\n leftPx,\n minimap: options.minimap\n });\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer.handle as WebGLFramebuffer | null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);\n gl.blitFramebuffer(\n 0,\n 0,\n framebuffer.width,\n framebuffer.height,\n targetX0,\n targetY0,\n targetX1,\n targetY1,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST\n );\n\n topPx += previewHeight + DEFAULT_MARGIN_PX;\n }\n } finally {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n state.flushing = false;\n }\n}\n\nfunction getOverlayRect(options: {\n framebuffer: Framebuffer;\n targetWidth: number;\n targetHeight: number;\n topPx: number;\n leftPx: number;\n minimap?: boolean;\n}): [number, number, number, number, number] {\n const {framebuffer, targetWidth, targetHeight, topPx, leftPx, minimap} = options;\n const maxWidth = minimap ? Math.max(Math.floor(targetWidth / 4), 1) : targetWidth;\n const maxHeight = minimap ? Math.max(Math.floor(targetHeight / 4), 1) : targetHeight;\n const scale = Math.min(maxWidth / framebuffer.width, maxHeight / framebuffer.height);\n const previewWidth = Math.max(Math.floor(framebuffer.width * scale), 1);\n const previewHeight = Math.max(Math.floor(framebuffer.height * scale), 1);\n const targetX0 = leftPx;\n const targetY0 = Math.max(targetHeight - topPx - previewHeight, 0);\n const targetX1 = targetX0 + previewWidth;\n const targetY1 = targetY0 + previewHeight;\n return [targetX0, targetY0, targetX1, targetY1, previewHeight];\n}\n\nfunction getDebugFramebufferState(device: Device): DebugFramebufferState {\n device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] ||= {\n flushing: false,\n queuedFramebuffers: []\n } satisfies DebugFramebufferState;\n return device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] as DebugFramebufferState;\n}\n\nfunction isFramebuffer(value: Framebuffer | Texture): value is Framebuffer {\n return 'colorAttachments' in value;\n}\n\nfunction isDefaultRenderPass(renderPass: RenderPass): boolean {\n const framebuffer = renderPass.props.framebuffer as {handle?: unknown} | null;\n return !framebuffer || framebuffer.handle === null;\n}\n\nfunction parseCssPixel(value: string | undefined, defaultValue: number): number {\n if (!value) {\n return defaultValue;\n }\n const parsedValue = Number.parseInt(value, 10);\n return Number.isFinite(parsedValue) ? parsedValue : defaultValue;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Fast partial deep equal for prop.\n *\n * @param a Prop\n * @param b Prop to compare against `a`\n * @param depth Depth to which to recurse in nested Objects/Arrays. Use 0 (default) for shallow comparison, -1 for infinite depth\n */\n/* eslint-disable complexity */\nexport function deepEqual(a: any, b: any, depth: number): boolean {\n if (a === b) {\n return true;\n }\n if (!depth || !a || !b) {\n return false;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(b)) {\n return false;\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n if (!b.hasOwnProperty(key)) {\n return false;\n }\n if (!deepEqual(a[key], b[key], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {getBufferLayoutAttributeNames, type BufferLayout} from '@luma.gl/core';\n\n/** BufferLayoutHelper is a helper class that should not be used directly by applications */\nexport class BufferLayoutHelper {\n bufferLayouts: BufferLayout[];\n\n constructor(bufferLayouts: BufferLayout[]) {\n this.bufferLayouts = bufferLayouts;\n }\n\n getBufferLayout(name: string): BufferLayout | null {\n return this.bufferLayouts.find(layout => layout.name === name) || null;\n }\n\n /** Get attribute names from a BufferLayout */\n getAttributeNamesForBuffer(bufferLayout: BufferLayout): string[] {\n return getBufferLayoutAttributeNames(bufferLayout);\n }\n\n mergeBufferLayouts(\n bufferLayouts1: BufferLayout[],\n bufferLayouts2: BufferLayout[]\n ): BufferLayout[] {\n const mergedLayouts = [...bufferLayouts1];\n for (const attribute of bufferLayouts2) {\n const index = mergedLayouts.findIndex(attribute2 => attribute2.name === attribute.name);\n if (index < 0) {\n mergedLayouts.push(attribute);\n } else {\n mergedLayouts[index] = attribute;\n }\n }\n return mergedLayouts;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n getBufferLayoutAttributeNames,\n getMinimumAttributeLocation,\n getShaderAttributeLocationMap,\n type BufferLayout,\n type ShaderLayout\n} from '@luma.gl/core';\n\nexport function sortedBufferLayoutByShaderSourceLocations(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[]\n): BufferLayout[] {\n const shaderLayoutMap = getShaderAttributeLocationMap(shaderLayout);\n\n const sortedLayout = bufferLayout.slice();\n sortedLayout.sort((a, b) => {\n const minLocationA = getMinimumAttributeLocation(\n getBufferLayoutAttributeNames(a).map(attributeName => shaderLayoutMap[attributeName])\n );\n const minLocationB = getMinimumAttributeLocation(\n getBufferLayoutAttributeNames(b).map(attributeName => shaderLayoutMap[attributeName])\n );\n\n return minLocationA - minLocationB;\n });\n\n return sortedLayout;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ComputeShaderLayout, ShaderLayout} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\ntype AnyShaderLayout = ShaderLayout | ComputeShaderLayout;\n\nexport function mergeShaderModuleBindingsIntoLayout<TShaderLayout extends AnyShaderLayout>(\n shaderLayout: TShaderLayout | null | undefined,\n modules: ShaderModule[]\n): TShaderLayout | null | undefined {\n if (!shaderLayout || !modules.some(module => module.bindingLayout?.length)) {\n return shaderLayout;\n }\n\n const mergedLayout = {\n ...shaderLayout,\n bindings: shaderLayout.bindings.map(binding => ({...binding}))\n } as TShaderLayout;\n\n if ('attributes' in (shaderLayout || {})) {\n (mergedLayout as ShaderLayout).attributes = (shaderLayout as ShaderLayout)?.attributes || [];\n }\n\n for (const module of modules) {\n for (const bindingLayout of module.bindingLayout || []) {\n for (const relatedBindingName of getRelatedBindingNames(bindingLayout.name)) {\n const binding = mergedLayout.bindings.find(\n candidate => candidate.name === relatedBindingName\n );\n if (binding?.group === 0) {\n binding.group = bindingLayout.group;\n }\n if (binding && bindingLayout.visibility !== undefined) {\n binding.visibility = bindingLayout.visibility;\n }\n }\n }\n }\n\n return mergedLayout;\n}\n\nexport function mergeInferredShaderLayout(\n shaderLayout: ShaderLayout | null | undefined,\n inferredShaderLayout: ShaderLayout | null | undefined,\n inferredAttributeNames: readonly string[] = []\n): ShaderLayout | null | undefined {\n if (!shaderLayout) {\n return inferredShaderLayout;\n }\n if (!inferredShaderLayout) {\n return shaderLayout;\n }\n\n return {\n ...shaderLayout,\n attributes: shaderLayout.attributes.length\n ? mergeAttributeLayouts(\n shaderLayout.attributes,\n inferredShaderLayout.attributes.filter(attribute =>\n inferredAttributeNames.includes(attribute.name)\n )\n )\n : inferredShaderLayout.attributes,\n bindings: mergeBindingLayouts(shaderLayout.bindings, inferredShaderLayout.bindings)\n };\n}\n\nexport function shaderModuleHasUniforms(module: ShaderModule): boolean {\n return Boolean(module.uniformTypes && !isObjectEmpty(module.uniformTypes));\n}\n\nexport function mergeShaderModules(\n explicitModules: ShaderModule[] | undefined,\n shaderInputModules: ShaderModule[] | undefined\n): ShaderModule[] {\n const modules: ShaderModule[] = [];\n const moduleNames = new Set<string>();\n\n for (const module of [...(explicitModules || []), ...(shaderInputModules || [])]) {\n if (!moduleNames.has(module.name)) {\n moduleNames.add(module.name);\n modules.push(module);\n }\n }\n\n return modules;\n}\n\n/** Returns binding-name aliases that should share the module-declared bind group. */\nfunction getRelatedBindingNames(bindingName: string): string[] {\n const bindingNames = new Set<string>([bindingName, `${bindingName}Uniforms`]);\n\n if (!bindingName.endsWith('Uniforms')) {\n bindingNames.add(`${bindingName}Sampler`);\n }\n\n return [...bindingNames];\n}\n\nfunction isObjectEmpty(obj: object): boolean {\n for (const _key in obj) {\n return false;\n }\n return true;\n}\n\nfunction mergeBindingLayouts<TBindingLayout extends ShaderLayout['bindings'][number]>(\n explicitBindings: TBindingLayout[],\n inferredBindings: TBindingLayout[]\n): TBindingLayout[] {\n const mergedBindings = explicitBindings.map(binding => ({...binding}));\n const explicitBindingNames = new Set(explicitBindings.map(binding => binding.name));\n const explicitBindingLocations = new Set(\n explicitBindings.map(binding => `${binding.group}:${binding.location}`)\n );\n\n for (const inferredBinding of inferredBindings) {\n const inferredBindingLocation = `${inferredBinding.group}:${inferredBinding.location}`;\n if (\n !explicitBindingNames.has(inferredBinding.name) &&\n !explicitBindingLocations.has(inferredBindingLocation)\n ) {\n mergedBindings.push({...inferredBinding});\n }\n }\n\n return mergedBindings;\n}\n\nfunction mergeAttributeLayouts(\n explicitAttributes: ShaderLayout['attributes'],\n inferredAttributes: ShaderLayout['attributes']\n): ShaderLayout['attributes'] {\n const mergedAttributes = explicitAttributes.map(attribute => ({...attribute}));\n const explicitAttributesByName = new Map(\n explicitAttributes.map(attribute => [attribute.name, attribute])\n );\n const explicitAttributesByLocation = new Map(\n explicitAttributes.map(attribute => [attribute.location, attribute])\n );\n\n for (const inferredAttribute of inferredAttributes) {\n const explicitByName = explicitAttributesByName.get(inferredAttribute.name);\n if (explicitByName) {\n if (\n explicitByName.type !== inferredAttribute.type ||\n explicitByName.location !== inferredAttribute.location\n ) {\n throw new Error(\n `Shader attribute \"${inferredAttribute.name}\" conflicts with its inferred type or location`\n );\n }\n continue;\n }\n\n const explicitByLocation = explicitAttributesByLocation.get(inferredAttribute.location);\n if (explicitByLocation) {\n throw new Error(\n `Shader attributes \"${explicitByLocation.name}\" and \"${inferredAttribute.name}\" both use location ${inferredAttribute.location}`\n );\n }\n\n mergedAttributes.push({...inferredAttribute});\n }\n\n return mergedAttributes;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CompositeShaderType} from '@luma.gl/core';\nimport {log} from '@luma.gl/core';\n// import type {VariableShaderType, UniformValue, UniformFormat, UniformInfoDevice, Texture, Sampler} from '@luma.gl/core';\nimport {\n getShaderModuleDependencies,\n ShaderModule,\n ShaderModuleUniformValue\n} from '@luma.gl/shadertools';\nimport {splitUniformsAndBindings} from './model/split-uniforms-and-bindings';\nimport type {TextureBindingSource} from './dynamic-texture/texture-binding-source';\n\n/** Shader binding accepted by ShaderInputs, including deferred texture binding sources. */\nexport type ShaderInputBinding = Binding | TextureBindingSource;\n\nexport type ShaderInputsOptions = {\n disableWarnings?: boolean;\n};\n\nexport type ShaderInputsProps<\n ShaderPropsT extends Partial<Record<string, Record<string, unknown>>>\n> = Partial<{[P in keyof ShaderPropsT]?: Partial<ShaderPropsT[P]>}> & {\n /** Shader resource bindings that are not owned by a shader module. */\n bindings?: Record<string, ShaderInputBinding>;\n};\n\ntype ShaderInputsModule = Pick<\n ShaderModule<any, any, any>,\n 'bindingLayout' | 'defaultUniforms' | 'dependencies' | 'getUniforms' | 'name' | 'uniformTypes'\n>;\n\n/**\n * ShaderInputs holds uniform and binding values for one or more shader modules,\n * - It can generate binary data for any uniform buffer\n * - It can manage a uniform buffer for each block\n * - It can update managed uniform buffers with a single call\n * - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.\n */\nexport class ShaderInputs<\n ShaderPropsT extends Partial<Record<string, Record<string, unknown>>> = Partial<\n Record<string, Record<string, unknown>>\n >\n> {\n options: Required<ShaderInputsOptions> = {\n disableWarnings: false\n };\n\n /** Registered shader modules, including resolved dependencies. */\n // @ts-ignore Fix typings\n modules: Readonly<{[P in keyof ShaderPropsT]: ShaderInputsModule}>;\n\n /** Stores the uniform values for each module */\n moduleUniforms: Record<keyof ShaderPropsT, Record<string, ShaderModuleUniformValue>>;\n /** Stores resource bindings for each module. */\n moduleBindings: Record<keyof ShaderPropsT, Record<string, ShaderInputBinding>>;\n /** Stores shader resource bindings that are not owned by a shader module. */\n directBindings: Record<string, ShaderInputBinding> = {};\n /** Tracks if uniforms have changed */\n // moduleUniformsChanged: Record<keyof ShaderPropsT, false | string>;\n\n /**\n * Creates shader input storage for one or more shader modules.\n * @param modules Initial shader modules keyed by module name.\n * @param options Shader input behavior options.\n */\n constructor(\n // @ts-ignore Fix typings\n modules: {[P in keyof ShaderPropsT]?: ShaderInputsModule},\n options?: ShaderInputsOptions\n ) {\n Object.assign(this.options, options);\n\n // Extract modules with dependencies\n const resolvedModules = getShaderModuleDependencies(\n Object.values(modules).filter(isShaderInputsModuleWithDependencies)\n );\n for (const resolvedModule of resolvedModules) {\n // @ts-ignore\n modules[resolvedModule.name] = resolvedModule;\n }\n\n log.log(1, 'Creating ShaderInputs with modules', Object.keys(modules))();\n\n // Store the module definitions and create storage for uniform values and binding values, per module\n // @ts-ignore Fix typings\n this.modules = modules as {[P in keyof ShaderPropsT]: ShaderInputsModule};\n this.moduleUniforms = {} as Record<\n keyof ShaderPropsT,\n Record<string, ShaderModuleUniformValue>\n >;\n this.moduleBindings = {} as Record<keyof ShaderPropsT, Record<string, ShaderInputBinding>>;\n\n // Initialize the modules\n for (const [name, module] of Object.entries(modules)) {\n if (module) {\n this._addModule(module);\n if (module.name && name !== module.name && !this.options.disableWarnings) {\n log.warn(`Module name: ${name} vs ${module.name}`)();\n }\n }\n }\n }\n\n /** Destroy */\n destroy(): void {}\n\n /**\n * Set module props\n */\n setProps(props: ShaderInputsProps<ShaderPropsT>): void {\n if (props.bindings) {\n Object.assign(this.directBindings, props.bindings);\n }\n\n for (const name of Object.keys(props)) {\n if (name === 'bindings') {\n continue;\n }\n\n const moduleName = name as keyof ShaderPropsT;\n const moduleProps = props[moduleName] || {};\n const module = this.modules[moduleName];\n if (!module) {\n // Ignore props for unregistered modules\n if (!this.options.disableWarnings) {\n log.warn(`Module ${name} not found`)();\n }\n } else {\n const oldUniforms = this.moduleUniforms[moduleName];\n const oldBindings = this.moduleBindings[moduleName];\n const uniformsAndBindings =\n module.getUniforms?.(moduleProps, oldUniforms) || (moduleProps as any);\n\n const {uniforms, bindings} = splitUniformsAndBindings(\n uniformsAndBindings,\n module.uniformTypes as Readonly<Record<string, CompositeShaderType>>\n );\n this.moduleUniforms[moduleName] = mergeModuleUniforms(\n oldUniforms as Record<string, ShaderModuleUniformValue>,\n uniforms,\n module.uniformTypes as Readonly<Record<string, CompositeShaderType>>\n );\n this.moduleBindings[moduleName] = {...oldBindings, ...bindings};\n // this.moduleUniformsChanged ||= moduleName;\n }\n\n // console.log(`setProps(${String(moduleName)}`, moduleName, this.moduleUniforms[moduleName])\n }\n }\n\n /** Returns registered shader modules, including resolved dependencies. */\n getModules(): ShaderModule[] {\n return Object.values(this.modules) as ShaderModule[];\n }\n\n /**\n * Adds shader modules that should participate in subsequent uniform and binding updates.\n * Module dependencies are resolved before new module state is initialized.\n * @param modules Shader modules to register after construction.\n */\n addModules(modules: ShaderInputsModule[]): void {\n const modulesToAdd = getShaderModuleDependencies(modules);\n\n for (const module of modulesToAdd) {\n const moduleName = module.name as keyof ShaderPropsT;\n if (!this.modules[moduleName]) {\n // @ts-ignore The ShaderInputs module registry is intentionally extended at runtime.\n this.modules[moduleName] = module;\n this._addModule(module);\n }\n }\n }\n\n /** Get all uniform values for all modules */\n getUniformValues(): Partial<\n Record<keyof ShaderPropsT, Record<string, ShaderModuleUniformValue>>\n > {\n return this.moduleUniforms;\n }\n\n /** Merges concrete and deferred bindings for the shader from the registered modules. */\n getBindingValues(): Record<string, ShaderInputBinding> {\n const bindings = {} as Record<string, ShaderInputBinding>;\n for (const moduleBindings of Object.values(this.moduleBindings)) {\n Object.assign(bindings, moduleBindings);\n }\n Object.assign(bindings, this.directBindings);\n return bindings;\n }\n\n /**\n * Gets binding values for a single shader module without flattening them into the full shader map.\n *\n * This is used by systems such as {@link ShaderPassRenderer} that execute one shader module at a\n * time and need the defaults for just that module.\n */\n getModuleBindingValues(\n moduleName: keyof ShaderPropsT | string\n ): Record<string, ShaderInputBinding> {\n const moduleBindings = this.moduleBindings[moduleName as keyof ShaderPropsT];\n return moduleBindings ? {...moduleBindings} : {};\n }\n\n // INTERNAL\n\n /** Return a debug table that can be used for console.table() or log.table() */\n getDebugTable(): Record<string, Record<string, unknown>> {\n const table: Record<string, Record<string, unknown>> = {};\n for (const [moduleName, module] of Object.entries(this.moduleUniforms)) {\n for (const [key, value] of Object.entries(module)) {\n table[`${moduleName}.${key}`] = {\n type: this.modules[moduleName].uniformTypes?.[key as keyof ShaderPropsT],\n value: String(value)\n };\n }\n }\n return table;\n }\n\n _addModule(module: ShaderInputsModule): void {\n const moduleName = module.name as keyof ShaderPropsT;\n // Get default uniforms from module\n this.moduleUniforms[moduleName] = mergeModuleUniforms(\n {},\n (module.defaultUniforms || {}) as Record<string, ShaderModuleUniformValue>,\n module.uniformTypes as Readonly<Record<string, CompositeShaderType>>\n );\n this.moduleBindings[moduleName] = {};\n }\n}\n\nfunction mergeModuleUniforms(\n currentUniforms: Record<string, ShaderModuleUniformValue> = {},\n nextUniforms: Record<string, ShaderModuleUniformValue> = {},\n uniformTypes: Readonly<Record<string, CompositeShaderType>> = {}\n): Record<string, ShaderModuleUniformValue> {\n const mergedUniforms = {...currentUniforms};\n for (const [key, value] of Object.entries(nextUniforms)) {\n if (value !== undefined) {\n mergedUniforms[key] = mergeModuleUniformValue(currentUniforms[key], value, uniformTypes[key]);\n }\n }\n return mergedUniforms;\n}\n\nfunction mergeModuleUniformValue(\n currentValue: ShaderModuleUniformValue | undefined,\n nextValue: ShaderModuleUniformValue,\n uniformType: CompositeShaderType | undefined\n): ShaderModuleUniformValue {\n if (!uniformType || typeof uniformType === 'string') {\n return cloneModuleUniformValue(nextValue);\n }\n\n if (Array.isArray(uniformType)) {\n if (isPackedUniformArrayValue(nextValue) || !Array.isArray(nextValue)) {\n return cloneModuleUniformValue(nextValue);\n }\n\n const currentArray: Array<ShaderModuleUniformValue | undefined> =\n Array.isArray(currentValue) && !isPackedUniformArrayValue(currentValue)\n ? [...currentValue]\n : [];\n const mergedArray = currentArray.slice();\n for (let index = 0; index < nextValue.length; index++) {\n const elementValue = nextValue[index];\n if (elementValue !== undefined) {\n mergedArray[index] = mergeModuleUniformValue(\n currentArray[index],\n elementValue,\n uniformType[0] as CompositeShaderType\n );\n }\n }\n return mergedArray;\n }\n\n if (!isPlainUniformObject(nextValue)) {\n return cloneModuleUniformValue(nextValue);\n }\n\n const uniformStruct = uniformType as Record<string, CompositeShaderType>;\n const currentObject = isPlainUniformObject(currentValue) ? currentValue : {};\n const mergedObject: Record<string, ShaderModuleUniformValue | undefined> = {...currentObject};\n for (const [key, value] of Object.entries(nextValue)) {\n if (value !== undefined) {\n mergedObject[key] = mergeModuleUniformValue(currentObject[key], value, uniformStruct[key]);\n }\n }\n return mergedObject as ShaderModuleUniformValue;\n}\n\nfunction cloneModuleUniformValue(value: ShaderModuleUniformValue): ShaderModuleUniformValue {\n if (ArrayBuffer.isView(value)) {\n return Array.prototype.slice.call(value) as ShaderModuleUniformValue;\n }\n\n if (Array.isArray(value)) {\n if (isPackedUniformArrayValue(value)) {\n return value.slice() as ShaderModuleUniformValue;\n }\n\n const compositeArray = value as ReadonlyArray<ShaderModuleUniformValue | undefined>;\n return compositeArray.map(element =>\n element === undefined ? undefined : cloneModuleUniformValue(element)\n ) as ShaderModuleUniformValue;\n }\n\n if (isPlainUniformObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, nestedValue]) => [\n key,\n nestedValue === undefined ? undefined : cloneModuleUniformValue(nestedValue)\n ])\n ) as ShaderModuleUniformValue;\n }\n\n return value;\n}\n\nfunction isPackedUniformArrayValue(\n value: unknown\n): value is ReadonlyArray<number> | ArrayBufferView {\n return (\n ArrayBuffer.isView(value) ||\n (Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number'))\n );\n}\n\nfunction isPlainUniformObject(\n value: unknown\n): value is Record<string, ShaderModuleUniformValue | undefined> {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !ArrayBuffer.isView(value)\n );\n}\n\nfunction isShaderInputsModuleWithDependencies(\n module: ShaderInputsModule | undefined\n): module is ShaderInputsModule & {dependencies: NonNullable<ShaderInputsModule['dependencies']>} {\n return Boolean(module?.dependencies);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CompositeShaderType, UniformValue} from '@luma.gl/core';\nimport type {ShaderModuleUniformValue} from '@luma.gl/shadertools';\nimport {isNumericArray} from '@math.gl/types';\nimport type {TextureBindingSource} from '../dynamic-texture/texture-binding-source';\n\n/** Shader input value routed through the binding map. */\ntype ShaderInputBinding = Binding | TextureBindingSource;\n\nexport function isUniformValue(value: unknown): value is UniformValue {\n return isNumericArray(value) || typeof value === 'number' || typeof value === 'boolean';\n}\n\ntype UniformsAndBindings = {\n bindings: Record<string, ShaderInputBinding>;\n uniforms: Record<string, ShaderModuleUniformValue>;\n};\n\nexport function splitUniformsAndBindings(\n uniforms: Record<string, ShaderInputBinding | ShaderModuleUniformValue>,\n uniformTypes: Readonly<Record<string, CompositeShaderType>> = {}\n): UniformsAndBindings {\n const result: UniformsAndBindings = {bindings: {}, uniforms: {}};\n Object.keys(uniforms).forEach(name => {\n const uniform = uniforms[name];\n if (Object.prototype.hasOwnProperty.call(uniformTypes, name) || isUniformValue(uniform)) {\n result.uniforms[name] = uniform as ShaderModuleUniformValue;\n } else {\n result.bindings[name] = uniform as ShaderInputBinding;\n }\n });\n\n return result;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {BufferMapCallback, BufferProps, Device, Binding as CoreBinding} from '@luma.gl/core';\nimport {Buffer} from '@luma.gl/core';\nimport {uid} from '../utils/uid';\n\n/** Controls whether a {@link DynamicBuffer} keeps a CPU-side debug mirror of recent writes. */\nexport type DynamicBufferDebugProps =\n | boolean\n | {\n /** Maximum number of bytes retained in {@link DynamicBuffer.debugData}. */\n maxByteLength?: number;\n };\n\n/** Construction props for a {@link DynamicBuffer}. */\nexport type DynamicBufferProps = Omit<BufferProps, 'handle' | 'onMapped'> & {\n /** Enables and optionally sizes the CPU-side debug mirror. */\n debugData?: DynamicBufferDebugProps;\n /** Existing immutable buffer to expose through this dynamic wrapper without copying. */\n buffer?: Buffer;\n /** Whether this dynamic wrapper should destroy an adopted `buffer`. Defaults to `true`. */\n ownsBuffer?: boolean;\n};\n\n/** Buffer-like source accepted by dynamic buffer range helpers. */\nexport type BufferBindingSource = Buffer | DynamicBuffer;\n\n/** Binding range that may point at either a {@link Buffer} or a {@link DynamicBuffer}. */\nexport type DynamicBufferRange = {\n /** Buffer source for the binding range. */\n buffer: BufferBindingSource;\n /** Byte offset into the current backing buffer. */\n offset?: number;\n /** Byte length of the binding range. */\n size?: number;\n};\n\n/** Generic buffer range binding accepted by engine binding resolution helpers. */\nexport type BufferRangeBinding = {\n /** Buffer source for the binding range. */\n buffer: BufferBindingSource;\n /** Byte offset into the current backing buffer. */\n offset?: number;\n /** Byte length of the binding range. */\n size?: number;\n};\n\nconst DEFAULT_MAX_DEBUG_DATA_BYTE_LENGTH = Buffer.DEBUG_DATA_MAX_LENGTH;\n\n/**\n * Mutable engine-level wrapper around an immutable core {@link Buffer}.\n *\n * `DynamicBuffer` keeps a stable application object while allowing the backing\n * GPU buffer to be replaced on resize. Engine classes such as {@link Model} and\n * {@link Material} resolve it to the current backing buffer at draw time and\n * invalidate cached bindings when {@link generation} changes.\n */\nexport class DynamicBuffer {\n /** Device that owns the backing buffer. */\n readonly device: Device;\n /** Application-provided or generated identifier. */\n readonly id: string;\n /** Ready promise provided for compatibility with other dynamic resources. */\n readonly ready: Promise<Buffer>;\n /** Usage flags applied to every backing buffer created by this wrapper. */\n readonly usage: number;\n /** Normalized buffer props reused when the backing buffer is recreated. */\n readonly props: Readonly<DynamicBufferProps>;\n\n /** Dynamic buffers are synchronously ready after construction. */\n isReady = true;\n /** Whether {@link destroy} has been called. */\n destroyed = false;\n /** Monotonic version that increments whenever the backing buffer is replaced. */\n generation = 0;\n /** Last update timestamp for writes, reads that populate debug data, or resize operations. */\n updateTimestamp: number;\n /** Optional CPU-side mirror of recent writes and readbacks for debugging. */\n debugData: ArrayBuffer = new ArrayBuffer(0);\n\n private readonly _debugDataEnabled: boolean;\n private readonly _maxDebugDataByteLength: number;\n private _ownsBuffer: boolean;\n private _buffer: Buffer;\n\n /** Current immutable core buffer backing this dynamic wrapper. */\n get buffer(): Buffer {\n return this._buffer;\n }\n\n /** Current byte length of the backing buffer. */\n get byteLength(): number {\n return this._buffer.byteLength;\n }\n\n /** String tag used by `Object.prototype.toString`. */\n get [Symbol.toStringTag](): string {\n return 'DynamicBuffer';\n }\n\n /** Human-readable debug string. */\n toString(): string {\n return `DynamicBuffer:\"${this.id}\":${this.byteLength}B`;\n }\n\n /** Compact serialization for assertion diffs and structured debug logs. */\n toJSON(): string {\n return this.toString();\n }\n\n /** Creates a dynamic buffer and its initial backing {@link Buffer}. */\n constructor(device: Device, props: DynamicBufferProps) {\n const {\n debugData: debugDataProps = false,\n buffer: adoptedBuffer,\n ownsBuffer = true,\n ...bufferProps\n } = props;\n if (adoptedBuffer && adoptedBuffer.device !== device) {\n throw new Error('DynamicBuffer adopted buffers must belong to the supplied device');\n }\n if (adoptedBuffer && (bufferProps.byteLength !== undefined || bufferProps.data !== undefined)) {\n throw new Error('DynamicBuffer cannot combine an adopted buffer with byteLength or data');\n }\n\n const id = props.id || adoptedBuffer?.id || uid('dynamic-buffer');\n const normalizedBufferProps: DynamicBufferProps = {\n ...bufferProps,\n id,\n usage: bufferProps.usage ?? adoptedBuffer?.usage,\n indexType: bufferProps.indexType ?? adoptedBuffer?.indexType\n };\n\n if ((normalizedBufferProps.usage || 0) & Buffer.INDEX && !normalizedBufferProps.indexType) {\n if (bufferProps.data instanceof Uint32Array) {\n normalizedBufferProps.indexType = 'uint32';\n } else if (bufferProps.data instanceof Uint16Array) {\n normalizedBufferProps.indexType = 'uint16';\n } else if (bufferProps.data instanceof Uint8Array) {\n normalizedBufferProps.indexType = 'uint8';\n }\n }\n\n delete normalizedBufferProps.data;\n delete normalizedBufferProps.byteOffset;\n\n this.device = device;\n this.id = id;\n this.props = normalizedBufferProps;\n this.usage = normalizedBufferProps.usage || 0;\n this._debugDataEnabled = Boolean(debugDataProps);\n this._maxDebugDataByteLength =\n typeof debugDataProps === 'object' && debugDataProps.maxByteLength !== undefined\n ? debugDataProps.maxByteLength\n : DEFAULT_MAX_DEBUG_DATA_BYTE_LENGTH;\n this._ownsBuffer = ownsBuffer;\n\n this._buffer = adoptedBuffer ?? this.device.createBuffer({...bufferProps, id});\n this.ready = Promise.resolve(this._buffer);\n this.updateTimestamp = this._buffer.updateTimestamp;\n\n this._resetDebugData(this._buffer.byteLength);\n if (bufferProps.data) {\n this._writeDebugData(bufferProps.data, bufferProps.byteOffset || 0);\n }\n }\n\n /**\n * Writes bytes into the current backing buffer.\n *\n * @param data - Bytes or typed-array view to upload.\n * @param byteOffset - Destination byte offset in the backing buffer.\n */\n write(data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView, byteOffset: number = 0): void {\n this._buffer.write(data, byteOffset);\n this._touch();\n this._writeDebugData(data, byteOffset);\n }\n\n /**\n * Maps the current backing buffer for writing and mirrors the written range when debug data is enabled.\n *\n * @param callback - Callback invoked with the mapped range.\n * @param byteOffset - Byte offset of the mapped range.\n * @param byteLength - Byte length of the mapped range.\n */\n async mapAndWriteAsync(\n callback: BufferMapCallback<void | Promise<void>>,\n byteOffset: number = 0,\n byteLength: number = this.byteLength - byteOffset\n ): Promise<void> {\n let copiedBytes: Uint8Array | null = null;\n await this._buffer.mapAndWriteAsync(\n async (arrayBuffer, lifetime) => {\n await callback(arrayBuffer, lifetime);\n copiedBytes = new Uint8Array(arrayBuffer.slice(0, byteLength));\n },\n byteOffset,\n byteLength\n );\n this._touch();\n if (copiedBytes) {\n this._writeDebugData(copiedBytes, byteOffset);\n }\n }\n\n /**\n * Reads bytes from the current backing buffer.\n *\n * @param byteOffset - Source byte offset in the backing buffer.\n * @param byteLength - Number of bytes to read.\n */\n async readAsync(\n byteOffset: number = 0,\n byteLength = this.byteLength - byteOffset\n ): Promise<Uint8Array> {\n const data = await this._buffer.readAsync(byteOffset, byteLength);\n if (this._writeDebugData(data, byteOffset)) {\n this._touch();\n }\n return data;\n }\n\n /**\n * Maps the current backing buffer for reading.\n *\n * @param callback - Callback invoked with the mapped range.\n * @param byteOffset - Byte offset of the mapped range.\n * @param byteLength - Byte length of the mapped range.\n */\n async mapAndReadAsync<T>(\n callback: BufferMapCallback<T>,\n byteOffset: number = 0,\n byteLength: number = this.byteLength - byteOffset\n ): Promise<T> {\n let copiedBytes: Uint8Array | null = null;\n const result = await this._buffer.mapAndReadAsync(\n async (arrayBuffer, lifetime) => {\n copiedBytes = new Uint8Array(arrayBuffer.slice(0));\n return await callback(arrayBuffer, lifetime);\n },\n byteOffset,\n byteLength\n );\n if (copiedBytes && this._writeDebugData(copiedBytes, byteOffset)) {\n this._touch();\n }\n return result;\n }\n\n /**\n * Replaces the backing buffer with a new size.\n *\n * @param options.byteLength - New backing buffer byte length.\n * @param options.preserveData - Copies bytes from the old buffer into the new buffer.\n * @param options.copyByteLength - Maximum number of bytes to copy when preserving data.\n * @returns `true` when a new backing buffer was created.\n */\n resize(options: {byteLength: number; preserveData?: boolean; copyByteLength?: number}): boolean {\n const {byteLength, preserveData = false} = options;\n if (byteLength === this.byteLength) {\n return false;\n }\n\n const copyByteLength = Math.min(\n options.copyByteLength ?? Math.min(this.byteLength, byteLength),\n this.byteLength,\n byteLength\n );\n\n const previousBuffer = this._buffer;\n const previousDebugData = this.debugData.slice(0);\n const {\n data: _initialData,\n byteOffset: _initialByteOffset,\n ...resizableBufferProps\n } = this.props;\n const nextBuffer = this.device.createBuffer({\n ...resizableBufferProps,\n byteLength\n });\n\n if (preserveData && copyByteLength > 0) {\n this._copyBufferContents(previousBuffer, nextBuffer, copyByteLength);\n }\n\n this._buffer = nextBuffer;\n this._resetDebugData(byteLength);\n if (preserveData && previousDebugData.byteLength > 0) {\n this._writeDebugData(previousDebugData, 0);\n }\n\n if (this._ownsBuffer) {\n previousBuffer.destroy();\n }\n this._ownsBuffer = true;\n this.generation++;\n this._touch();\n return true;\n }\n\n /**\n * Grows the backing buffer when the requested size exceeds the current size.\n *\n * @param byteLength - Minimum required byte length.\n * @param options.preserveData - Copies existing bytes when growth is required.\n * @returns `true` when the backing buffer grew.\n */\n ensureSize(byteLength: number, options?: {preserveData?: boolean}): boolean {\n if (byteLength <= this.byteLength) {\n return false;\n }\n\n return this.resize({\n byteLength,\n preserveData: options?.preserveData\n });\n }\n\n /**\n * Returns the current backing buffer or a range binding over it.\n *\n * @param range - Optional byte range for uniform/storage buffer bindings.\n */\n getBinding(range?: {offset?: number; size?: number}): CoreBinding {\n if (range?.offset === undefined && range?.size === undefined) {\n return this._buffer;\n }\n\n return {\n buffer: this._buffer,\n offset: range?.offset,\n size: range?.size\n };\n }\n\n /** Destroys the current backing buffer and clears debug data. */\n destroy(): void {\n if (!this.destroyed) {\n if (this._ownsBuffer) {\n this._buffer.destroy();\n }\n this.destroyed = true;\n this.debugData = new ArrayBuffer(0);\n }\n }\n\n private _copyBufferContents(\n sourceBuffer: Buffer,\n destinationBuffer: Buffer,\n byteLength: number\n ): void {\n const copyByteLength =\n this.device.type === 'webgpu' ? Math.ceil(byteLength / 4) * 4 : byteLength;\n const commandEncoder = this.device.createCommandEncoder();\n commandEncoder.copyBufferToBuffer({\n sourceBuffer,\n destinationBuffer,\n size: copyByteLength\n });\n this.device.submit(commandEncoder.finish());\n }\n\n private _touch(): void {\n this.updateTimestamp = this.device.incrementTimestamp();\n }\n\n private _resetDebugData(byteLength: number): void {\n if (!this._debugDataEnabled) {\n this.debugData = new ArrayBuffer(0);\n return;\n }\n\n this.debugData = new ArrayBuffer(Math.min(byteLength, this._maxDebugDataByteLength));\n }\n\n private _writeDebugData(\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView,\n byteOffset: number\n ): boolean {\n if (\n !this._debugDataEnabled ||\n this.debugData.byteLength === 0 ||\n byteOffset >= this.debugData.byteLength\n ) {\n return false;\n }\n\n const source = ArrayBuffer.isView(data)\n ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n : new Uint8Array(data);\n const target = new Uint8Array(this.debugData);\n const copyByteLength = Math.min(source.byteLength, target.byteLength - byteOffset);\n target.set(source.subarray(0, copyByteLength), byteOffset);\n return copyByteLength > 0;\n }\n}\n\n/** Returns `true` when a value has the structural shape of a buffer range binding. */\nexport function isBufferRangeBinding(binding: unknown): binding is BufferRangeBinding {\n return (\n binding !== null &&\n typeof binding === 'object' &&\n 'buffer' in (binding as Record<string, unknown>)\n );\n}\n\n/** Returns `true` when a range binding points at a {@link DynamicBuffer}. */\nexport function isDynamicBufferRange(binding: unknown): binding is DynamicBufferRange {\n return isBufferRangeBinding(binding) && binding.buffer instanceof DynamicBuffer;\n}\n\n/** Extracts a {@link DynamicBuffer} from a direct binding or range binding. */\nexport function getDynamicBufferFromBinding(binding: unknown): DynamicBuffer | null {\n if (binding instanceof DynamicBuffer) {\n return binding;\n }\n\n if (isBufferRangeBinding(binding) && binding.buffer instanceof DynamicBuffer) {\n return binding.buffer;\n }\n\n return null;\n}\n\n/** Resolves a static or dynamic buffer source to the current core {@link Buffer}. */\nexport function resolveBufferBindingSource(buffer: BufferBindingSource): Buffer {\n return buffer instanceof DynamicBuffer ? buffer.buffer : buffer;\n}\n\n/** Resolves a dynamic buffer range to a core buffer range over the current backing buffer. */\nexport function resolveDynamicBufferRangeBinding(binding: DynamicBufferRange): {\n buffer: Buffer;\n offset?: number;\n size?: number;\n} {\n return resolveBufferRangeBinding(binding);\n}\n\n/** Resolves a buffer range to a core buffer range over the current backing buffer. */\nexport function resolveBufferRangeBinding(binding: BufferRangeBinding): {\n buffer: Buffer;\n offset?: number;\n size?: number;\n} {\n return {\n buffer: resolveBufferBindingSource(binding.buffer),\n offset: binding.offset,\n size: binding.size\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, BindingDeclaration, ComputeShaderLayout, ShaderLayout} from '@luma.gl/core';\nimport {getShaderLayoutBinding} from '@luma.gl/core';\n\n/** Reflected shader binding declarations that accept texture-like engine sources. */\nexport type TextureBindingLayout = Extract<\n BindingDeclaration,\n {type: 'texture' | 'external-texture'}\n>;\n\n/**\n * Engine-level source that resolves into a concrete core texture binding for one shader slot.\n */\nexport interface TextureBindingSource {\n /** Stable resource identifier used in loading and debug messages. */\n readonly id: string;\n /** Whether the source can resolve a concrete binding for the current draw. */\n readonly isReady: boolean;\n /** Monotonic binding generation advanced when concrete draw bindings may need recreation. */\n readonly generation: number;\n /** Device timestamp of the most recent source content or binding identity update. */\n readonly updateTimestamp: number;\n\n /**\n * Resolves this source for one reflected texture binding declaration.\n * @param bindingLayout Reflected `texture` or `external-texture` shader slot.\n * @returns A concrete core binding, or `null` while the source is not ready.\n */\n resolveTextureBinding(bindingLayout: TextureBindingLayout): Binding | null;\n}\n\n/**\n * Returns whether a value is an engine source that resolves texture bindings at draw time.\n * @param value Candidate engine binding value.\n * @returns Whether `value` implements {@link TextureBindingSource}.\n */\nexport function isTextureBindingSource(value: unknown): value is TextureBindingSource {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'resolveTextureBinding' in value &&\n typeof value.resolveTextureBinding === 'function'\n );\n}\n\n/**\n * Returns whether a shader binding declaration accepts a texture binding source.\n * @param bindingLayout Candidate reflected shader binding declaration.\n * @returns Whether `bindingLayout` is a `texture` or `external-texture` declaration.\n */\nexport function isTextureBindingLayout(\n bindingLayout: BindingDeclaration | null\n): bindingLayout is TextureBindingLayout {\n return bindingLayout?.type === 'texture' || bindingLayout?.type === 'external-texture';\n}\n\n/**\n * Looks up the reflected texture binding declaration for one engine binding name.\n *\n * @remarks\n * Models and materials can be asked for bindings before a shader layout has been reflected.\n * In that legacy empty-layout path, `fallbackGroup` synthesizes an ordinary `texture` slot so\n * copied `DynamicTexture` and `VideoTexture` bindings keep their pre-reflection behavior.\n * Native WebGPU `texture_external` resolution still requires the real reflected declaration.\n *\n * @param shaderLayout Reflected shader bindings, or an empty binding list before reflection.\n * @param bindingName Engine binding name to resolve against the shader layout.\n * @param options Texture binding lookup behavior.\n * @param options.fallbackGroup Bind group for the legacy empty-layout ordinary texture fallback.\n * @returns The reflected or synthesized texture binding declaration, or `null` for non-texture slots.\n */\nexport function getTextureBindingLayout(\n shaderLayout: Pick<ShaderLayout | ComputeShaderLayout, 'bindings'>,\n bindingName: string,\n options?: {fallbackGroup?: number}\n): TextureBindingLayout | null {\n const bindingLayout = getShaderLayoutBinding(shaderLayout, bindingName, {\n ignoreWarnings: true\n });\n if (isTextureBindingLayout(bindingLayout)) {\n return bindingLayout;\n }\n return shaderLayout.bindings.length === 0 && options?.fallbackGroup !== undefined\n ? {\n type: 'texture',\n name: bindingName,\n group: options.fallbackGroup,\n location: 0\n }\n : null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n Binding,\n BindingsByGroup,\n CommandEncoder,\n ComputeShaderLayout,\n Device,\n ShaderLayout\n} from '@luma.gl/core';\nimport {Buffer, ExternalTexture, Texture, TextureView, UniformStore} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport {\n DynamicBuffer,\n type DynamicBufferRange,\n getDynamicBufferFromBinding,\n isBufferRangeBinding,\n resolveBufferRangeBinding\n} from '../dynamic-buffer/dynamic-buffer';\nimport {\n getTextureBindingLayout,\n isTextureBindingSource,\n type TextureBindingSource\n} from '../dynamic-texture/texture-binding-source';\nimport {ShaderInputs} from '../shader-inputs';\nimport {shaderModuleHasUniforms} from '../utils/shader-module-utils';\nimport {uid} from '../utils/uid';\nimport {\n getModuleNameFromUniformBinding,\n MATERIAL_BIND_GROUP,\n MaterialFactory\n} from './material-factory';\n\ntype MaterialModuleProps = Partial<Record<string, Record<string, unknown>>>;\n/** Resource accepted by one material binding slot. */\ntype MaterialBinding = Binding | TextureBindingSource | DynamicBuffer | DynamicBufferRange;\ntype MaterialBindings = Record<string, MaterialBinding>;\n/** Shader layout subset needed while resolving texture binding sources. */\ntype AnyShaderLayout = Pick<ShaderLayout | ComputeShaderLayout, 'bindings'>;\ntype MaterialPropsUpdate<TModuleProps extends MaterialModuleProps> = Partial<{\n [P in keyof TModuleProps]?: Partial<TModuleProps[P]>;\n}>;\n\n/** Construction props for one typed {@link Material}. */\nexport type MaterialProps<\n TModuleProps extends MaterialModuleProps = MaterialModuleProps,\n TBindings extends MaterialBindings = MaterialBindings\n> = {\n /** Optional application-provided identifier. */\n id?: string;\n /** Factory that owns the material schema. */\n factory?: MaterialFactory<TModuleProps, TBindings>;\n /** Optional pre-created shader inputs for the material modules. */\n shaderInputs?: ShaderInputs<TModuleProps>;\n /** Shader modules used when a factory is not supplied. */\n modules?: ShaderModule[];\n /** Initial material-owned resource bindings. */\n bindings?: Partial<TBindings>;\n};\n\n/** Structural overrides applied when cloning a {@link Material}. */\nexport type MaterialCloneProps<\n TModuleProps extends MaterialModuleProps = MaterialModuleProps,\n TBindings extends MaterialBindings = MaterialBindings\n> = {\n /** Optional identifier for the cloned material. */\n id?: string;\n /** Replacement material-owned resource bindings. */\n bindings?: Partial<TBindings>;\n /** Additional uniform/module props applied to the clone. */\n moduleProps?: MaterialPropsUpdate<TModuleProps>;\n /** Optional full replacement shader-input store. */\n shaderInputs?: ShaderInputs<TModuleProps>;\n};\n\n/**\n * Material owns bind group `3` resources and uniforms for one material instance.\n *\n * `setProps()` mutates uniform values in place. Structural resource changes are\n * expressed through `clone({...})`, which creates a new material identity.\n */\nexport class Material<\n TModuleProps extends MaterialModuleProps = MaterialModuleProps,\n TBindings extends MaterialBindings = MaterialBindings\n> {\n /** Application-provided identifier. */\n readonly id: string;\n /** Device that owns the material resources. */\n readonly device: Device;\n /** Factory that defines the material schema. */\n readonly factory: MaterialFactory<TModuleProps, TBindings>;\n /** Shader inputs for the material-owned modules. */\n readonly shaderInputs: ShaderInputs<TModuleProps>;\n /** Internal binding store including uniform buffers and resource bindings. */\n readonly bindings: Record<string, MaterialBinding> = {};\n\n private _uniformStore: UniformStore;\n private _bindGroupCacheToken: object = {};\n private _dynamicResourceGenerations: Record<string, number> = {};\n\n constructor(device: Device, props: MaterialProps<TModuleProps, TBindings> = {}) {\n this.id = props.id || uid('material');\n this.device = device;\n\n this.factory =\n props.factory ||\n new MaterialFactory<TModuleProps, TBindings>(device, {\n modules: props.modules || props.shaderInputs?.getModules() || []\n });\n\n const moduleMap = Object.fromEntries(\n (props.shaderInputs?.getModules() || this.factory.modules).map(module => [\n module.name,\n module\n ])\n ) as {[P in keyof TModuleProps]?: ShaderModule[] extends never ? never : any};\n this.shaderInputs = props.shaderInputs || new ShaderInputs<TModuleProps>(moduleMap);\n this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules);\n\n for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) {\n if (this.ownsModule(moduleName) && shaderModuleHasUniforms(module)) {\n const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName);\n this.bindings[`${moduleName}Uniforms`] = uniformBuffer;\n }\n }\n\n this.updateShaderInputs();\n if (props.bindings) {\n this._replaceOwnedBindings(props.bindings);\n }\n }\n\n /** Destroys managed uniform-buffer resources owned by this material. */\n destroy(): void {\n this._uniformStore.destroy();\n }\n\n /** Creates a new material variant with optional structural and uniform overrides. */\n clone(\n props: MaterialCloneProps<TModuleProps, TBindings> = {}\n ): Material<TModuleProps, TBindings> {\n const material = this.factory.createMaterial({\n id: props.id,\n shaderInputs: props.shaderInputs,\n bindings: {\n ...this.getResourceBindings(),\n ...props.bindings\n }\n });\n\n if (!props.shaderInputs) {\n material.setProps(this.shaderInputs.getUniformValues() as MaterialPropsUpdate<TModuleProps>);\n }\n if (props.moduleProps) {\n material.setProps(props.moduleProps);\n }\n material.updateShaderInputs();\n return material;\n }\n\n /** Returns `true` if this material owns the supplied binding name. */\n ownsBinding(bindingName: string): boolean {\n return this.factory.ownsBinding(bindingName);\n }\n\n /** Returns `true` if this material owns the supplied shader module. */\n ownsModule(moduleName: string): boolean {\n return this.factory.ownsModule(moduleName);\n }\n\n /** Updates material uniform/module props in place without changing material identity. */\n setProps(props: MaterialPropsUpdate<TModuleProps>): void {\n this.shaderInputs.setProps(props);\n }\n\n /**\n * Updates managed uniform buffers and shader-input-owned bindings.\n *\n * @param commandEncoder - Optional encoder used to order material uniform\n * uploads with subsequent draw commands.\n */\n updateShaderInputs(commandEncoder?: CommandEncoder): void {\n this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(), commandEncoder);\n const didChange = this._setOwnedBindings(this.shaderInputs.getBindingValues());\n if (didChange) {\n this._bindGroupCacheToken = {};\n }\n }\n\n /** Returns the material-owned resource bindings without internal uniform buffers. */\n getResourceBindings(): Partial<TBindings> {\n const resourceBindings = {} as Partial<TBindings>;\n\n for (const [name, binding] of Object.entries(this.bindings)) {\n if (!getModuleNameFromUniformBinding(name)) {\n (resourceBindings as Record<string, MaterialBinding>)[name] = binding;\n }\n }\n\n return resourceBindings;\n }\n\n /**\n * Returns resolved bindings, including internal uniform buffers and ready texture sources.\n * @param shaderLayout Reflected bindings used to select copied or external texture resolution.\n */\n getBindings(\n shaderLayout: AnyShaderLayout = {bindings: []}\n ): Partial<{[K in keyof TBindings]: Binding}> & Record<string, Binding> {\n this._syncDynamicResourceGenerations();\n\n const validBindings = {} as Partial<{[K in keyof TBindings]: Binding}> &\n Record<string, Binding>;\n const validBindingsMap = validBindings as Record<string, Binding>;\n for (const [name, binding] of Object.entries(this.bindings)) {\n if (isTextureBindingSource(binding)) {\n const bindingLayout = getTextureBindingLayout(shaderLayout, name, {\n fallbackGroup: MATERIAL_BIND_GROUP\n });\n const resolvedBinding = bindingLayout ? binding.resolveTextureBinding(bindingLayout) : null;\n if (resolvedBinding) {\n validBindingsMap[name] = resolvedBinding;\n }\n } else if (binding instanceof DynamicBuffer) {\n validBindingsMap[name] = binding.buffer;\n } else if (isBufferRangeBinding(binding)) {\n validBindingsMap[name] = resolveBufferRangeBinding(binding);\n } else {\n validBindingsMap[name] = binding;\n }\n }\n\n this._syncDynamicResourceGenerations();\n return validBindings;\n }\n\n /**\n * Packages resolved material bindings into logical bind group `3`.\n * @param shaderLayout Reflected bindings used to select copied or external texture resolution.\n */\n getBindingsByGroup(shaderLayout: AnyShaderLayout = {bindings: []}): BindingsByGroup {\n return this.factory.getBindingsByGroup(this.getBindings(shaderLayout));\n }\n\n /** Returns the stable bind-group cache token for the requested bind group. */\n getBindGroupCacheKey(group: number): object | null {\n this._syncDynamicResourceGenerations();\n return group === MATERIAL_BIND_GROUP ? this._bindGroupCacheToken : null;\n }\n\n /** Returns the latest update timestamp across material-owned resources. */\n getBindingsUpdateTimestamp(): number {\n let timestamp = 0;\n for (const binding of Object.values(this.bindings)) {\n if (binding instanceof TextureView) {\n timestamp = Math.max(timestamp, binding.texture.updateTimestamp);\n } else if (\n binding instanceof Buffer ||\n binding instanceof Texture ||\n binding instanceof ExternalTexture\n ) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (binding instanceof DynamicBuffer) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (isTextureBindingSource(binding)) {\n timestamp = binding.isReady ? Math.max(timestamp, binding.updateTimestamp) : Infinity;\n } else if (isBufferRangeBinding(binding)) {\n timestamp = Math.max(\n timestamp,\n binding.buffer instanceof DynamicBuffer\n ? binding.buffer.updateTimestamp\n : binding.buffer.updateTimestamp\n );\n }\n }\n return timestamp;\n }\n\n /** Replaces owned resource bindings and invalidates the material cache identity when needed. */\n private _replaceOwnedBindings(bindings: Partial<TBindings>): void {\n const didChange = this._setOwnedBindings(bindings);\n if (didChange) {\n this._bindGroupCacheToken = {};\n }\n }\n\n private _setOwnedBindings(\n bindings: Partial<TBindings> | Record<string, MaterialBinding>\n ): boolean {\n let didChange = false;\n\n for (const [name, binding] of Object.entries(bindings)) {\n if (binding === undefined) {\n continue;\n }\n if (!this.ownsBinding(name)) {\n continue;\n }\n\n if (this.bindings[name] !== binding) {\n this.bindings[name] = binding;\n didChange = true;\n }\n }\n\n return didChange;\n }\n\n /** Invalidates the material bind-group key when deferred binding generations change. */\n private _syncDynamicResourceGenerations(): void {\n const nextGenerations: Record<string, number> = {};\n let didChange = false;\n\n for (const [name, binding] of Object.entries(this.bindings)) {\n const dynamicResourceGeneration = getDynamicResourceGeneration(binding);\n if (dynamicResourceGeneration !== null) {\n nextGenerations[name] = dynamicResourceGeneration;\n if (this._dynamicResourceGenerations[name] !== dynamicResourceGeneration) {\n didChange = true;\n }\n }\n }\n\n if (\n Object.keys(nextGenerations).length !== Object.keys(this._dynamicResourceGenerations).length\n ) {\n didChange = true;\n }\n\n this._dynamicResourceGenerations = nextGenerations;\n if (didChange) {\n this._bindGroupCacheToken = {};\n }\n }\n}\n\n/**\n * Returns the generation tracked for one deferred material binding.\n * @param binding Material binding candidate.\n * @returns Deferred binding generation, or `null` for stable concrete bindings.\n */\nfunction getDynamicResourceGeneration(binding: MaterialBinding): number | null {\n if (isTextureBindingSource(binding)) {\n return binding.generation;\n }\n\n return getDynamicBufferFromBinding(binding)?.generation ?? null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, BindingsByGroup, Device} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport type {TextureBindingSource} from '../dynamic-texture/texture-binding-source';\nimport {ShaderInputs} from '../shader-inputs';\nimport type {Material, MaterialProps} from './material';\nimport {Material as MaterialClass} from './material';\n\ntype MaterialModuleProps = Partial<Record<string, Record<string, unknown>>>;\ntype MaterialBindings = Record<\n string,\n | Binding\n | TextureBindingSource\n | import('../dynamic-buffer/dynamic-buffer').DynamicBuffer\n | import('../dynamic-buffer/dynamic-buffer').DynamicBufferRange\n>;\n\n/** Logical bind-group slot reserved for material-owned bindings. */\nexport const MATERIAL_BIND_GROUP = 3;\n\n/** Construction props for {@link MaterialFactory}. */\nexport type MaterialFactoryProps = {\n /** Shader modules that define the material schema for bind group `3`. */\n modules?: ShaderModule[];\n};\n\n/**\n * Creates typed {@link Material} instances for a stable material binding schema.\n *\n * @example\n * ```ts\n * const pbrFactory = new MaterialFactory<\n * {pbrMaterial: PBRMaterialUniforms},\n * PBRMaterialBindings\n * >(device, {modules: [pbrMaterial]});\n * const pbr = pbrFactory.createMaterial();\n * pbr.setProps({pbrMaterial: {baseColorFactor: [1, 0, 0, 1]}});\n * const pbrVariant = pbr.clone({bindings: {pbr_baseColorSampler: texture}});\n * ```\n *\n * @example\n * ```ts\n * const phongFactory = new MaterialFactory<\n * {phongMaterial: PhongMaterialProps},\n * {}\n * >(device, {modules: [phongMaterial]});\n * const phong = phongFactory.createMaterial();\n * phong.setProps({phongMaterial: {ambient: 0.4, diffuse: 0.7}});\n * const phongVariant = phong.clone({moduleProps: {phongMaterial: {shininess: 64}}});\n * ```\n *\n * @example\n * ```ts\n * const gouraudFactory = new MaterialFactory<\n * {gouraudMaterial: GouraudMaterialProps},\n * {}\n * >(device, {modules: [gouraudMaterial]});\n * const gouraud = gouraudFactory.createMaterial();\n * gouraud.setProps({gouraudMaterial: {ambient: 0.25}});\n * const gouraudVariant = gouraud.clone({moduleProps: {gouraudMaterial: {diffuse: 0.8}}});\n * ```\n */\nexport class MaterialFactory<\n TModuleProps extends MaterialModuleProps = MaterialModuleProps,\n TBindings extends MaterialBindings = MaterialBindings\n> {\n /** Device that creates materials for this schema. */\n readonly device: Device;\n /** Shader modules that define the material schema. */\n readonly modules: ShaderModule[];\n\n private _materialBindingNames: Set<string>;\n private _materialModuleNames: Set<string>;\n\n constructor(device: Device, props: MaterialFactoryProps = {}) {\n this.device = device;\n this.modules = props.modules || [];\n\n const shaderInputs = new ShaderInputs(\n Object.fromEntries(this.modules.map(module => [module.name, module]))\n );\n this._materialBindingNames = getMaterialBindingNames(shaderInputs);\n this._materialModuleNames = getMaterialModuleNames(shaderInputs);\n }\n\n /** Creates one typed material instance for this factory's schema. */\n createMaterial(\n props: Omit<MaterialProps<TModuleProps, TBindings>, 'factory' | 'modules'> = {}\n ): Material<TModuleProps, TBindings> {\n return new MaterialClass<TModuleProps, TBindings>(this.device, {\n ...props,\n factory: this\n });\n }\n\n /** Returns the logical material-owned resource binding names. */\n getBindingNames(): string[] {\n return Array.from(this._materialBindingNames);\n }\n\n /** Returns `true` when the supplied binding belongs to this material schema. */\n ownsBinding(bindingName: string): boolean {\n if (this._materialBindingNames.has(bindingName)) {\n return true;\n }\n\n const aliasedModuleName = getModuleNameFromUniformBinding(bindingName);\n return aliasedModuleName ? this._materialModuleNames.has(aliasedModuleName) : false;\n }\n\n /** Returns `true` when the supplied shader module is owned by this material schema. */\n ownsModule(moduleName: string): boolean {\n return this._materialModuleNames.has(moduleName);\n }\n\n /** Packages resolved material bindings into bind group `3`. */\n getBindingsByGroup(\n bindings: Partial<{[K in keyof TBindings]: Binding}> & Record<string, Binding>\n ): BindingsByGroup {\n return Object.keys(bindings).length > 0 ? {[MATERIAL_BIND_GROUP]: bindings} : {};\n }\n}\n\n/** Returns the module name corresponding to an auto-generated `*Uniforms` binding. */\nexport function getModuleNameFromUniformBinding(bindingName: string): string | null {\n return bindingName.endsWith('Uniforms') ? bindingName.slice(0, -'Uniforms'.length) : null;\n}\n\nfunction getMaterialBindingNames(shaderInputs: ShaderInputs): Set<string> {\n const bindingNames = new Set<string>();\n\n for (const module of Object.values(shaderInputs.modules)) {\n for (const binding of module.bindingLayout || []) {\n if (binding.group === MATERIAL_BIND_GROUP) {\n bindingNames.add(binding.name);\n }\n }\n }\n\n return bindingNames;\n}\n\nfunction getMaterialModuleNames(shaderInputs: ShaderInputs): Set<string> {\n const moduleNames = new Set<string>();\n\n for (const module of Object.values(shaderInputs.modules)) {\n if (\n module.name &&\n module.bindingLayout?.some(\n binding => binding.group === MATERIAL_BIND_GROUP && binding.name === module.name\n )\n ) {\n moduleNames.add(module.name);\n }\n }\n\n return moduleNames;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Buffer, BufferRange, TransformFeedback, RenderPassProps} from '@luma.gl/core';\nimport {getPassthroughFS} from '@luma.gl/shadertools';\nimport {Model} from '../model/model';\nimport type {ModelProps} from '../model/model';\n\nconst GL_INTERLEAVED_ATTRIBS = 0x8c8c;\nconst GL_SEPARATE_ATTRIBS = 0x8c8d;\n\n/**\n * Properties for creating a {@link BufferTransform}\n * @note Only works under WebGL2.\n */\nexport type BufferTransformProps = Omit<ModelProps, 'fs'> & {\n /** Optional fragment shader - normally not used in transforms */\n fs?: ModelProps['fs']; // override as optional\n /** bufferMode when binding varyings\n * https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/transformFeedbackVaryings\n */\n feedbackBufferMode?: 'interleaved' | 'separate';\n /** A list of named outputs corresponding to shader declarations (varyings in WebGL) */\n outputs?: string[];\n /** @deprecated Use run({outputBuffers}) instead - Map of output buffers that the shaders will write results of computations to */\n feedbackBuffers?: Record<string, Buffer | BufferRange>;\n};\n\n/**\n * Manages a WebGL program (pipeline) for buffer\u2192buffer transforms.\n * @note Only works under WebGL2.\n */\nexport class BufferTransform {\n readonly device: Device;\n readonly model: Model;\n readonly transformFeedback: TransformFeedback;\n\n static defaultProps: Required<BufferTransformProps> = {\n ...Model.defaultProps,\n feedbackBufferMode: 'separate',\n outputs: undefined!,\n feedbackBuffers: undefined!\n };\n\n static isSupported(device: Device): boolean {\n return device?.info?.type === 'webgl';\n }\n\n constructor(device: Device, props: BufferTransformProps = BufferTransform.defaultProps) {\n if (!BufferTransform.isSupported(device)) {\n throw new Error('BufferTransform not yet implemented on WebGPU');\n }\n\n this.device = device;\n\n this.model = new Model(this.device, {\n id: props.id || 'buffer-transform-model',\n fs: props.fs || getPassthroughFS(),\n topology: props.topology || 'point-list',\n varyings: props.outputs || props.varyings,\n ...props,\n bufferMode:\n props.bufferMode ||\n (props.feedbackBufferMode === 'interleaved' ? GL_INTERLEAVED_ATTRIBS : GL_SEPARATE_ATTRIBS)\n });\n\n this.transformFeedback = this.device.createTransformFeedback({\n layout: this.model.pipeline.shaderLayout,\n // @ts-expect-error TODO\n buffers: props.feedbackBuffers\n });\n\n this.model.setTransformFeedback(this.transformFeedback);\n }\n\n /** Destroy owned resources. */\n destroy(): void {\n if (this.model) {\n this.model.destroy();\n }\n }\n\n /** @deprecated Use {@link destroy}. */\n delete(): void {\n this.destroy();\n }\n\n /** Run one transform loop. */\n run(\n options?: RenderPassProps & {\n inputBuffers?: Record<string, Buffer>;\n outputBuffers?: Record<string, Buffer | BufferRange>;\n }\n ): void {\n if (options?.inputBuffers) {\n this.model.setAttributes(options.inputBuffers);\n }\n if (options?.outputBuffers) {\n this.transformFeedback.setBuffers(options.outputBuffers);\n }\n const renderPass = this.device.beginRenderPass({discard: true, ...options});\n this.model.draw(renderPass);\n renderPass.end();\n }\n\n // DEPRECATED METHODS\n\n /** @deprecated App knows what buffers it is passing in - Returns the {@link Buffer} or {@link BufferRange} for given varying name. */\n getBuffer(varyingName: string): Buffer | BufferRange | null {\n return this.transformFeedback.getBuffer(varyingName);\n }\n\n /** @deprecated App knows what buffers it is passing in - Reads the {@link Buffer} or {@link BufferRange} for given varying name. */\n readAsync(varyingName: string): Promise<Uint8Array> {\n const result = this.getBuffer(varyingName);\n if (!result) {\n throw new Error('BufferTransform#getBuffer');\n }\n if (result instanceof Buffer) {\n return result.readAsync();\n }\n const {buffer, byteOffset = 0, byteLength = buffer.byteLength} = result;\n return buffer.readAsync(byteOffset, byteLength);\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Buffer, Device, Framebuffer, RenderPassProps, Sampler, Texture} from '@luma.gl/core';\nimport {getPassthroughFS} from '@luma.gl/shadertools';\nimport {Model, ModelProps} from '../model/model';\nimport {uid} from '../utils/uid';\n\n/**\n * Properties for creating a {@link TextureTransform}\n */\nexport type TextureTransformProps = Omit<ModelProps, 'fs'> & {\n fs?: ModelProps['fs']; // override as optional\n /** @deprecated TODO(donmccurdy): Needed? */\n inject?: Record<string, string>;\n /** @deprecated TODO(donmccurdy): Needed? */\n framebuffer?: Framebuffer;\n /** @deprecated TODO(donmccurdy): Model already handles this? */\n sourceBuffers?: Record<string, Buffer>;\n /** @deprecated TODO(donmccurdy): Model already handles this? */\n sourceTextures?: Record<string, Texture>;\n targetTexture: Texture;\n targetTextureChannels: 1 | 2 | 3 | 4;\n targetTextureVarying: string;\n};\n\ntype TextureBinding = {\n sourceBuffers: Record<string, Buffer>;\n sourceTextures: Record<string, Texture>;\n targetTexture: Texture;\n framebuffer?: Framebuffer;\n};\n\nconst FS_OUTPUT_VARIABLE = 'transform_output';\n\n/**\n * Creates a pipeline for texture\u2192texture transforms.\n * @deprecated\n */\nexport class TextureTransform {\n readonly device: Device;\n readonly model: Model;\n readonly sampler: Sampler;\n\n currentIndex = 0;\n samplerTextureMap: Record<string, any> | null = null;\n bindings: TextureBinding[] = []; // each element is an object : {sourceTextures, targetTexture, framebuffer}\n resources: Record<string, any> = {}; // resources to be deleted\n\n constructor(device: Device, props: TextureTransformProps) {\n this.device = device;\n\n // For precise picking of element IDs.\n this.sampler = device.createSampler({\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n minFilter: 'nearest',\n magFilter: 'nearest',\n mipmapFilter: 'nearest'\n });\n\n this.model = new Model(this.device, {\n id: props.id || uid('texture-transform-model'),\n fs:\n props.fs ||\n getPassthroughFS({\n input: props.targetTextureVarying,\n inputChannels: props.targetTextureChannels,\n output: FS_OUTPUT_VARIABLE\n }),\n vertexCount: props.vertexCount, // TODO(donmccurdy): Naming?\n ...props\n });\n\n this._initialize(props);\n Object.seal(this);\n }\n\n // Delete owned resources.\n destroy(): void {\n this.model.destroy();\n for (const binding of this.bindings) {\n binding.framebuffer?.destroy();\n }\n }\n\n /** @deprecated Use {@link destroy}. */\n delete(): void {\n this.destroy();\n }\n\n run(options?: RenderPassProps): void {\n const {framebuffer} = this.bindings[this.currentIndex];\n const renderPass = this.device.beginRenderPass({framebuffer, ...options});\n this.model.draw(renderPass);\n renderPass.end();\n this.device.submit();\n }\n\n getTargetTexture(): Texture {\n const {targetTexture} = this.bindings[this.currentIndex];\n return targetTexture;\n }\n\n getFramebuffer(): Framebuffer | undefined {\n const currentResources = this.bindings[this.currentIndex];\n return currentResources.framebuffer;\n }\n\n // Private\n\n _initialize(props: TextureTransformProps): void {\n this._updateBindings(props);\n }\n\n _updateBindings(props: TextureTransformProps) {\n this.bindings[this.currentIndex] = this._updateBinding(this.bindings[this.currentIndex], props);\n }\n\n _updateBinding(\n binding: TextureBinding,\n {sourceBuffers, sourceTextures, targetTexture}: TextureTransformProps\n ): TextureBinding {\n if (!binding) {\n binding = {\n sourceBuffers: {},\n sourceTextures: {},\n // @ts-expect-error\n targetTexture: null\n };\n }\n Object.assign(binding.sourceTextures, sourceTextures);\n Object.assign(binding.sourceBuffers, sourceBuffers);\n if (targetTexture) {\n binding.targetTexture = targetTexture;\n const {width, height} = targetTexture;\n // TODO(donmccurdy): When is this called, and is this expected?\n if (binding.framebuffer) {\n binding.framebuffer.destroy();\n }\n binding.framebuffer = this.device.createFramebuffer({\n id: 'transform-framebuffer',\n width,\n height,\n colorAttachments: [targetTexture]\n });\n binding.framebuffer.resize({width, height});\n }\n return binding;\n }\n\n // set texture filtering parameters on source textures.\n _setSourceTextureParameters(): void {\n const index = this.currentIndex;\n const {sourceTextures} = this.bindings[index];\n for (const name in sourceTextures) {\n sourceTextures[name].sampler = this.sampler;\n }\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// ClipSpace\nimport {Device} from '@luma.gl/core';\nimport {Model, ModelProps} from '../model/model';\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\nconst CLIPSPACE_VERTEX_SHADER_WGSL = /* wgsl */ `\\\nstruct VertexInputs {\n @location(0) clipSpacePositions: vec2<f32>,\n @location(1) texCoords: vec2<f32>,\n @location(2) coordinates: vec2<f32>\n}\n\nstruct FragmentInputs {\n @builtin(position) Position : vec4<f32>,\n @location(0) position : vec2<f32>,\n @location(1) coordinate : vec2<f32>,\n @location(2) uv : vec2<f32>\n};\n\n@vertex\nfn vertexMain(inputs: VertexInputs) -> FragmentInputs {\n var outputs: FragmentInputs;\n outputs.Position = vec4(inputs.clipSpacePositions, 0., 1.);\n outputs.position = inputs.clipSpacePositions;\n outputs.coordinate = inputs.coordinates;\n outputs.uv = inputs.texCoords;\n return outputs;\n}\n`;\n\nconst CLIPSPACE_VERTEX_SHADER = /* glsl */ `\\\n#version 300 es\nin vec2 clipSpacePositions;\nin vec2 texCoords;\nin vec2 coordinates;\n\nout vec2 position;\nout vec2 coordinate;\nout vec2 uv;\n\nvoid main(void) {\n gl_Position = vec4(clipSpacePositions, 0., 1.);\n position = clipSpacePositions;\n coordinate = coordinates;\n uv = texCoords;\n}\n`;\n\n/* eslint-disable indent, no-multi-spaces */\nconst POSITIONS = [-1, -1, 1, -1, -1, 1, 1, 1];\n\n/** Props for ClipSpace */\nexport type ClipSpaceProps = Omit<ModelProps, 'vs' | 'vertexCount' | 'geometry'>;\n\n/**\n * A flat geometry that covers the \"visible area\" that the GPU renders.\n */\nexport class ClipSpace extends Model {\n constructor(device: Device, props: ClipSpaceProps) {\n const TEX_COORDS = POSITIONS.map(coord => (coord === -1 ? 0 : coord));\n\n // For WGSL we need to append the supplied fragment shader to the default vertex shader source\n if (props.source) {\n props = {...props, source: `${CLIPSPACE_VERTEX_SHADER_WGSL}\\n${props.source}`};\n }\n\n super(device, {\n id: props.id || uid('clip-space'),\n ...props,\n vs: CLIPSPACE_VERTEX_SHADER,\n vertexCount: 4,\n geometry: new Geometry({\n topology: 'triangle-strip',\n vertexCount: 4,\n attributes: {\n clipSpacePositions: {size: 2, value: new Float32Array(POSITIONS)},\n texCoords: {size: 2, value: new Float32Array(TEX_COORDS)},\n coordinates: {size: 2, value: new Float32Array(TEX_COORDS)}\n }\n })\n });\n }\n}\n", "// luma.gl, MIT license\n// Copyright (c) vis.gl contributors\n\nimport type {\n TextureProps,\n SamplerProps,\n TextureView,\n Device,\n TextureFormat,\n TextureReadOptions\n} from '@luma.gl/core';\n\nimport {Buffer, Texture, Sampler, log} from '@luma.gl/core';\n\n// import {loadImageBitmap} from '../application-utils/load-file';\nimport {uid} from '../utils/uid';\nimport {\n // cube constants\n type TextureCubeFace,\n TEXTURE_CUBE_FACE_MAP,\n // texture slice/mip data types\n type TextureSubresource,\n // props (dimension + data)\n type TextureDataProps,\n type TextureDataAsyncProps,\n // combined data for different texture types\n type Texture1DData,\n type Texture2DData,\n type Texture3DData,\n type TextureArrayData,\n type TextureCubeArrayData,\n type TextureCubeData,\n // Helpers\n getTextureSizeFromData,\n resolveTextureImageFormat,\n getTexture1DSubresources,\n getTexture2DSubresources,\n getTexture3DSubresources,\n getTextureCubeSubresources,\n getTextureArraySubresources,\n getTextureCubeArraySubresources\n} from './texture-data';\nimport type {TextureBindingLayout, TextureBindingSource} from './texture-binding-source';\n\n/**\n * Properties for a dynamic texture\n */\nexport type DynamicTextureProps = Omit<TextureProps, 'data' | 'mipLevels' | 'width' | 'height'> &\n TextureDataAsyncProps & {\n /** Generate mipmaps after creating textures and setting data */\n mipmaps?: boolean;\n /** nipLevels can be set to 'auto' to generate max number of mipLevels */\n mipLevels?: number | 'auto';\n /** Width - can be auto-calculated when initializing from ExternalImage */\n width?: number;\n /** Height - can be auto-calculated when initializing from ExternalImage */\n height?: number;\n };\n\n/**\n * Dynamic Textures\n *\n * - Mipmaps - DynamicTexture can generate mipmaps for textures (WebGPU does not provide built-in mipmap generation).\n *\n * - Texture initialization and updates - complex textures (2d array textures, cube textures, 3d textures) need multiple images\n * `DynamicTexture` provides an API that makes it easy to provide the required data.\n *\n * - Texture resizing - Textures are immutable in WebGPU, meaning that they cannot be resized after creation.\n * DynamicTexture provides a `resize()` method that internally creates a new texture with the same parameters\n * but a different size.\n *\n * - Async image data initialization - It is often very convenient to be able to initialize textures with promises\n * returned by image or data loading functions, as it allows a callback-free linear style of programming.\n *\n * @note GPU Textures are quite complex objects, with many subresources and modes of usage.\n * The `DynamicTexture` class allows luma.gl to provide some support for working with textures\n * without accumulating excessive complexity in the core Texture class which is designed as an immutable nature of GPU resource.\n */\nexport class DynamicTexture implements TextureBindingSource {\n readonly device: Device;\n readonly id: string;\n\n /** Props with defaults resolved (except `data` which is processed separately) */\n props: Readonly<Required<DynamicTextureProps>>;\n\n /** Created resources */\n private _texture: Texture | null = null;\n private _sampler: Sampler | null = null;\n private _view: TextureView | null = null;\n\n /** Ready when GPU texture has been created and data (if any) uploaded */\n readonly ready: Promise<Texture>;\n isReady = false;\n destroyed = false;\n /** Monotonic version that increments whenever texture, view, or sampler identity changes. */\n generation = 0;\n /** Last update timestamp for texture content, readiness, or identity changes. */\n updateTimestamp: number;\n\n private resolveReady: (t: Texture) => void = () => {};\n private rejectReady: (error: Error) => void = () => {};\n\n get texture(): Texture {\n if (!this._texture) throw new Error('Texture not initialized yet');\n return this._texture;\n }\n get sampler(): Sampler {\n if (!this._sampler) throw new Error('Sampler not initialized yet');\n return this._sampler;\n }\n get view(): TextureView {\n if (!this._view) throw new Error('View not initialized yet');\n return this._view;\n }\n\n get [Symbol.toStringTag]() {\n return 'DynamicTexture';\n }\n toString(): string {\n const width = this._texture?.width ?? this.props.width ?? '?';\n const height = this._texture?.height ?? this.props.height ?? '?';\n return `DynamicTexture:\"${this.id}\":${width}x${height}px:(${this.isReady ? 'ready' : 'loading...'})`;\n }\n\n /**\n * Resolves this ready dynamic texture as an ordinary copied texture binding.\n * @param _bindingLayout Reflected texture-like shader slot; DynamicTexture always resolves a copied texture.\n * @returns The copied texture, or `null` while the source is not ready.\n */\n resolveTextureBinding(_bindingLayout: TextureBindingLayout): Texture | null {\n return this.isReady ? this.texture : null;\n }\n\n constructor(device: Device, props: DynamicTextureProps) {\n this.device = device;\n\n const id = uid('dynamic-texture');\n // NOTE: We avoid holding on to data to make sure it can be garbage collected.\n const originalPropsWithAsyncData = props;\n this.props = {...DynamicTexture.defaultProps, id, ...props, data: null};\n this.id = this.props.id;\n\n this.ready = new Promise<Texture>((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n this.updateTimestamp = this.device.incrementTimestamp();\n\n this.initAsync(originalPropsWithAsyncData);\n }\n\n /** @note Fire and forget; caller can await `ready` */\n async initAsync(originalPropsWithAsyncData: DynamicTextureProps): Promise<void> {\n try {\n // TODO - Accept URL string for 2D: turn into ExternalImage promise\n // const dataProps =\n // typeof props.data === 'string' && (props.dimension ?? '2d') === '2d'\n // ? ({dimension: '2d', data: loadImageBitmap(props.data)} as const)\n // : {};\n\n const propsWithSyncData = await this._loadAllData(originalPropsWithAsyncData);\n this._checkNotDestroyed();\n const subresources = propsWithSyncData.data\n ? getTextureSubresources({\n ...propsWithSyncData,\n width: originalPropsWithAsyncData.width,\n height: originalPropsWithAsyncData.height,\n format: originalPropsWithAsyncData.format\n })\n : [];\n const userProvidedFormat =\n 'format' in originalPropsWithAsyncData && originalPropsWithAsyncData.format !== undefined;\n const userProvidedUsage =\n 'usage' in originalPropsWithAsyncData && originalPropsWithAsyncData.usage !== undefined;\n\n // Deduce size when not explicitly provided\n // TODO - what about depth?\n const deduceSize = (): {width: number; height: number} => {\n if (this.props.width && this.props.height) {\n return {width: this.props.width, height: this.props.height};\n }\n\n const size = getTextureSizeFromData(propsWithSyncData);\n if (size) {\n return size;\n }\n\n return {width: this.props.width || 1, height: this.props.height || 1};\n };\n\n const size = deduceSize();\n if (!size || size.width <= 0 || size.height <= 0) {\n throw new Error(`${this} size could not be determined or was zero`);\n }\n\n // Normalize caller-provided subresources into one validated mip chain description.\n const textureData = analyzeTextureSubresources(this.device, subresources, size, {\n format: userProvidedFormat ? originalPropsWithAsyncData.format : undefined\n });\n const resolvedFormat = textureData.format ?? this.props.format;\n\n // Create a minimal TextureProps and validate via `satisfies`\n const baseTextureProps = {\n ...this.props,\n ...size,\n format: resolvedFormat,\n mipLevels: 1, // temporary; updated below\n data: undefined\n } satisfies TextureProps;\n\n if (this.device.isTextureFormatCompressed(resolvedFormat) && !userProvidedUsage) {\n baseTextureProps.usage = Texture.SAMPLE | Texture.COPY_DST;\n }\n\n // Explicit mip arrays take ownership of the mip chain; otherwise we may auto-generate it.\n const shouldGenerateMipmaps =\n this.props.mipmaps &&\n !textureData.hasExplicitMipChain &&\n !this.device.isTextureFormatCompressed(resolvedFormat);\n\n if (this.device.type === 'webgpu' && shouldGenerateMipmaps) {\n const requiredUsage =\n this.props.dimension === '3d'\n ? Texture.SAMPLE | Texture.STORAGE | Texture.COPY_DST | Texture.COPY_SRC\n : Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST | Texture.COPY_SRC;\n baseTextureProps.usage |= requiredUsage;\n }\n\n // Compute mip levels (auto clamps to max)\n const maxMips = this.device.getMipLevelCount(baseTextureProps.width, baseTextureProps.height);\n const desired = textureData.hasExplicitMipChain\n ? textureData.mipLevels\n : this.props.mipLevels === 'auto'\n ? maxMips\n : Math.max(1, Math.min(maxMips, this.props.mipLevels ?? 1));\n\n const finalTextureProps: TextureProps = {...baseTextureProps, mipLevels: desired};\n\n this._texture = this.device.createTexture(finalTextureProps);\n this._sampler = this.texture.sampler;\n this._view = this.texture.view;\n this._touchGeneration();\n\n // Upload data if provided\n if (textureData.subresources.length) {\n this._setTextureSubresources(textureData.subresources);\n }\n\n if (this.props.mipmaps && !textureData.hasExplicitMipChain && !shouldGenerateMipmaps) {\n log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)();\n }\n\n if (shouldGenerateMipmaps) {\n this.generateMipmaps();\n }\n\n this.isReady = true;\n this.resolveReady(this.texture);\n\n log.info(1, `${this} created`)();\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.rejectReady(err);\n }\n }\n\n destroy(): void {\n if (this._texture) {\n this._texture.destroy();\n this._texture = null;\n this._sampler = null;\n this._view = null;\n }\n this.isReady = false;\n this.destroyed = true;\n }\n\n generateMipmaps(): void {\n if (this.device.type === 'webgl') {\n this.texture.generateMipmapsWebGL();\n this._touch();\n } else if (this.device.type === 'webgpu') {\n this.device.generateMipmapsWebGPU(this.texture);\n this._touch();\n } else {\n log.warn(`${this} mipmaps not supported on ${this.device.type}`);\n }\n }\n\n /** Set sampler or create one from props */\n setSampler(sampler: Sampler | SamplerProps = {}): void {\n this._checkReady();\n const s = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);\n this.texture.setSampler(s);\n this._sampler = s;\n this._touchGeneration();\n }\n\n /**\n * Copies texture contents into a GPU buffer and waits until the copy is complete.\n * The caller owns the returned buffer and must destroy it when finished.\n */\n async readBuffer(options: TextureReadOptions = {}): Promise<Buffer> {\n if (!this.isReady) {\n await this.ready;\n }\n\n const width = options.width ?? this.texture.width;\n const height = options.height ?? this.texture.height;\n const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth;\n const layout = this.texture.computeMemoryLayout({width, height, depthOrArrayLayers});\n\n const buffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n\n this.texture.readBuffer(\n {\n ...options,\n width,\n height,\n depthOrArrayLayers\n },\n buffer\n );\n\n const fence = this.device.createFence();\n await fence.signaled;\n fence.destroy();\n\n return buffer;\n }\n\n /** Reads texture contents back to CPU memory. */\n async readAsync(options: TextureReadOptions = {}): Promise<ArrayBuffer> {\n if (!this.isReady) {\n await this.ready;\n }\n\n const width = options.width ?? this.texture.width;\n const height = options.height ?? this.texture.height;\n const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth;\n const layout = this.texture.computeMemoryLayout({width, height, depthOrArrayLayers});\n\n const buffer = await this.readBuffer(options);\n const data = await buffer.readAsync(0, layout.byteLength);\n buffer.destroy();\n return data.buffer instanceof ArrayBuffer ? data.buffer : data.slice().buffer;\n }\n\n /**\n * Resize by cloning the underlying immutable texture.\n * Does not copy contents; caller may need to re-upload and/or regenerate mips.\n */\n resize(size: {width: number; height: number}): boolean {\n this._checkReady();\n\n if (size.width === this.texture.width && size.height === this.texture.height) {\n return false;\n }\n const prev = this.texture;\n this._texture = prev.clone(size);\n this._sampler = this.texture.sampler;\n this._view = this.texture.view;\n\n prev.destroy();\n this._touchGeneration();\n log.info(`${this} resized`);\n return true;\n }\n\n /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\n getCubeFaceIndex(face: TextureCubeFace): number {\n const index = TEXTURE_CUBE_FACE_MAP[face];\n if (index === undefined) throw new Error(`Invalid cube face: ${face}`);\n return index;\n }\n\n /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\n getCubeArrayFaceIndex(cubeIndex: number, face: TextureCubeFace): number {\n return 6 * cubeIndex + this.getCubeFaceIndex(face);\n }\n\n /** @note experimental: Set multiple mip levels (1D) */\n setTexture1DData(data: Texture1DData): void {\n this._checkReady();\n if (this.texture.props.dimension !== '1d') {\n throw new Error(`${this} is not 1d`);\n }\n const subresources = getTexture1DSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */\n setTexture2DData(lodData: Texture2DData, z: number = 0): void {\n this._checkReady();\n if (this.texture.props.dimension !== '2d') {\n throw new Error(`${this} is not 2d`);\n }\n\n const subresources = getTexture2DSubresources(z, lodData);\n this._setTextureSubresources(subresources);\n }\n\n /** 3D: multiple depth slices, each may carry multiple mip levels */\n setTexture3DData(data: Texture3DData): void {\n if (this.texture.props.dimension !== '3d') {\n throw new Error(`${this} is not 3d`);\n }\n const subresources = getTexture3DSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** 2D array: multiple layers, each may carry multiple mip levels */\n setTextureArrayData(data: TextureArrayData): void {\n if (this.texture.props.dimension !== '2d-array') {\n throw new Error(`${this} is not 2d-array`);\n }\n const subresources = getTextureArraySubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Cube: 6 faces, each may carry multiple mip levels */\n setTextureCubeData(data: TextureCubeData): void {\n if (this.texture.props.dimension !== 'cube') {\n throw new Error(`${this} is not cube`);\n }\n const subresources = getTextureCubeSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Cube array: multiple cubes (faces\u00D7layers), each face may carry multiple mips */\n setTextureCubeArrayData(data: TextureCubeArrayData): void {\n if (this.texture.props.dimension !== 'cube-array') {\n throw new Error(`${this} is not cube-array`);\n }\n const subresources = getTextureCubeArraySubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Sets multiple mip levels on different `z` slices (depth/array index) */\n private _setTextureSubresources(subresources: TextureSubresource[]): void {\n // If user supplied multiple mip levels, warn if auto-mips also requested\n // if (lodArray.length > 1 && this.props.mipmaps !== false) {\n // log.warn(\n // `Texture ${this.id}: provided multiple LODs and also requested mipmap generation.`\n // )();\n // }\n\n for (const subresource of subresources) {\n const {z, mipLevel} = subresource;\n switch (subresource.type) {\n case 'external-image':\n const {image, flipY} = subresource;\n this.texture.copyExternalImage({image, z, mipLevel, flipY});\n break;\n case 'texture-data':\n const {data, textureFormat} = subresource;\n if (textureFormat && textureFormat !== this.texture.format) {\n throw new Error(\n `${this} mip level ${mipLevel} uses format \"${textureFormat}\" but texture format is \"${this.texture.format}\"`\n );\n }\n this.texture.writeData(data.data, {\n x: 0,\n y: 0,\n z,\n width: data.width,\n height: data.height,\n depthOrArrayLayers: 1,\n mipLevel\n });\n break;\n default:\n throw new Error('Unsupported 2D mip-level payload');\n }\n }\n if (subresources.length > 0) {\n this._touch();\n }\n }\n\n // ------------------ helpers ------------------\n\n /** Recursively resolve all promises in data structures */\n private async _loadAllData(props: TextureDataAsyncProps): Promise<TextureDataProps> {\n const syncData = await awaitAllPromises(props.data);\n const dimension = (props.dimension ?? '2d') as TextureDataProps['dimension'];\n return {dimension, data: syncData ?? null} as TextureDataProps;\n }\n\n private _checkNotDestroyed() {\n if (this.destroyed) {\n log.warn(`${this} already destroyed`);\n }\n }\n\n private _checkReady() {\n if (!this.isReady) {\n log.warn(`${this} Cannot perform this operation before ready`);\n }\n }\n\n private _touch(): void {\n this.updateTimestamp = this.device.incrementTimestamp();\n }\n\n private _touchGeneration(): void {\n this.generation++;\n this._touch();\n }\n\n static defaultProps: Required<DynamicTextureProps> = {\n ...Texture.defaultProps,\n dimension: '2d',\n data: null,\n mipmaps: false\n };\n}\n\ntype TextureSubresourceAnalysis = {\n readonly subresources: TextureSubresource[];\n readonly mipLevels: number;\n readonly format?: TextureFormat;\n readonly hasExplicitMipChain: boolean;\n};\n\n// Flatten dimension-specific texture data into one list of uploadable subresources.\nfunction getTextureSubresources(\n props: TextureDataProps & Partial<Pick<TextureProps, 'width' | 'height' | 'format'>>\n): TextureSubresource[] {\n if (!props.data) {\n return [];\n }\n\n const baseLevelSize =\n props.width && props.height ? {width: props.width, height: props.height} : undefined;\n const textureFormat = 'format' in props ? props.format : undefined;\n\n switch (props.dimension) {\n case '1d':\n return getTexture1DSubresources(props.data);\n case '2d':\n return getTexture2DSubresources(0, props.data, baseLevelSize, textureFormat);\n case '3d':\n return getTexture3DSubresources(props.data);\n case '2d-array':\n return getTextureArraySubresources(props.data);\n case 'cube':\n return getTextureCubeSubresources(props.data);\n case 'cube-array':\n return getTextureCubeArraySubresources(props.data);\n default:\n throw new Error(`Unhandled dimension ${(props as TextureDataProps).dimension}`);\n }\n}\n\n// Resolve a consistent texture format and the longest mip chain valid across all slices.\nfunction analyzeTextureSubresources(\n device: Device,\n subresources: TextureSubresource[],\n size: {width: number; height: number},\n options: {format?: TextureFormat}\n): TextureSubresourceAnalysis {\n if (subresources.length === 0) {\n return {\n subresources,\n mipLevels: 1,\n format: options.format,\n hasExplicitMipChain: false\n };\n }\n\n const groupedSubresources = new Map<number, TextureSubresource[]>();\n for (const subresource of subresources) {\n const group = groupedSubresources.get(subresource.z) ?? [];\n group.push(subresource);\n groupedSubresources.set(subresource.z, group);\n }\n\n const hasExplicitMipChain = subresources.some(subresource => subresource.mipLevel > 0);\n let resolvedFormat = options.format;\n let resolvedMipLevels = Number.POSITIVE_INFINITY;\n const validSubresources: TextureSubresource[] = [];\n\n for (const [z, sliceSubresources] of groupedSubresources) {\n // Validate each slice independently, then keep only the mip levels that are valid everywhere.\n const sortedSubresources = [...sliceSubresources].sort(\n (left, right) => left.mipLevel - right.mipLevel\n );\n const baseLevel = sortedSubresources[0];\n if (!baseLevel || baseLevel.mipLevel !== 0) {\n throw new Error(`DynamicTexture: slice ${z} is missing mip level 0`);\n }\n\n const baseSize = getTextureSubresourceSize(device, baseLevel);\n if (baseSize.width !== size.width || baseSize.height !== size.height) {\n throw new Error(\n `DynamicTexture: slice ${z} base level dimensions ${baseSize.width}x${baseSize.height} do not match expected ${size.width}x${size.height}`\n );\n }\n\n const baseFormat = getTextureSubresourceFormat(baseLevel);\n if (baseFormat) {\n if (resolvedFormat && resolvedFormat !== baseFormat) {\n throw new Error(\n `DynamicTexture: slice ${z} base level format \"${baseFormat}\" does not match texture format \"${resolvedFormat}\"`\n );\n }\n resolvedFormat = baseFormat;\n }\n\n const mipLevelLimit =\n resolvedFormat && device.isTextureFormatCompressed(resolvedFormat)\n ? // Block-compressed formats cannot have mips smaller than a single compression block.\n getMaxCompressedMipLevels(device, baseSize.width, baseSize.height, resolvedFormat)\n : device.getMipLevelCount(baseSize.width, baseSize.height);\n\n let validMipLevelsForSlice = 0;\n for (\n let expectedMipLevel = 0;\n expectedMipLevel < sortedSubresources.length;\n expectedMipLevel++\n ) {\n const subresource = sortedSubresources[expectedMipLevel];\n // Stop at the first gap so callers can provide extra trailing data without breaking creation.\n if (!subresource || subresource.mipLevel !== expectedMipLevel) {\n break;\n }\n if (expectedMipLevel >= mipLevelLimit) {\n break;\n }\n\n const subresourceSize = getTextureSubresourceSize(device, subresource);\n const expectedWidth = Math.max(1, baseSize.width >> expectedMipLevel);\n const expectedHeight = Math.max(1, baseSize.height >> expectedMipLevel);\n if (subresourceSize.width !== expectedWidth || subresourceSize.height !== expectedHeight) {\n break;\n }\n\n const subresourceFormat = getTextureSubresourceFormat(subresource);\n if (subresourceFormat) {\n if (!resolvedFormat) {\n resolvedFormat = subresourceFormat;\n }\n // Later mip levels must stay on the same format as the validated base level.\n if (subresourceFormat !== resolvedFormat) {\n break;\n }\n }\n\n validMipLevelsForSlice++;\n validSubresources.push(subresource);\n }\n\n resolvedMipLevels = Math.min(resolvedMipLevels, validMipLevelsForSlice);\n }\n\n const mipLevels = Number.isFinite(resolvedMipLevels) ? Math.max(1, resolvedMipLevels) : 1;\n\n return {\n // Keep every slice trimmed to the same mip count so the texture shape stays internally consistent.\n subresources: validSubresources.filter(subresource => subresource.mipLevel < mipLevels),\n mipLevels,\n format: resolvedFormat,\n hasExplicitMipChain\n };\n}\n\n// Read the per-level format using the transitional textureFormat -> format fallback rules.\nfunction getTextureSubresourceFormat(subresource: TextureSubresource): TextureFormat | undefined {\n if (subresource.type !== 'texture-data') {\n return undefined;\n }\n return subresource.textureFormat ?? resolveTextureImageFormat(subresource.data);\n}\n\n// Resolve dimensions from either raw bytes or external-image subresources.\nfunction getTextureSubresourceSize(\n device: Device,\n subresource: TextureSubresource\n): {width: number; height: number} {\n switch (subresource.type) {\n case 'external-image':\n return device.getExternalImageSize(subresource.image);\n case 'texture-data':\n return {width: subresource.data.width, height: subresource.data.height};\n default:\n throw new Error('Unsupported texture subresource');\n }\n}\n\n// Count the mip levels that stay at or above one compression block in each dimension.\nfunction getMaxCompressedMipLevels(\n device: Device,\n baseWidth: number,\n baseHeight: number,\n format: TextureFormat\n): number {\n const {blockWidth = 1, blockHeight = 1} = device.getTextureFormatInfo(format);\n let mipLevels = 1;\n for (let mipLevel = 1; ; mipLevel++) {\n const width = Math.max(1, baseWidth >> mipLevel);\n const height = Math.max(1, baseHeight >> mipLevel);\n if (width < blockWidth || height < blockHeight) {\n break;\n }\n mipLevels++;\n }\n return mipLevels;\n}\n\n// HELPERS\n\n/** Resolve all promises in a nested data structure */\nasync function awaitAllPromises(x: any): Promise<any> {\n x = await x;\n if (Array.isArray(x)) {\n return await Promise.all(x.map(awaitAllPromises));\n }\n if (x && typeof x === 'object' && x.constructor === Object) {\n const object: Record<string, any> = x;\n const values = await Promise.all(Object.values(object).map(awaitAllPromises));\n const keys = Object.keys(object);\n const resolvedObject: Record<string, any> = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObject[keys[i]] = values[i];\n }\n return resolvedObject;\n }\n return x;\n}\n\n// /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */\n// setTexture2DData(lodData: Texture2DData, z: number = 0): void {\n// this._checkReady();\n\n// const lodArray = this._normalizeTexture2DData(lodData);\n\n// // If user supplied multiple mip levels, warn if auto-mips also requested\n// if (lodArray.length > 1 && this.props.mipmaps !== false) {\n// log.warn(\n// `Texture ${this.id}: provided multiple LODs and also requested mipmap generation.`\n// )();\n// }\n\n// for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) {\n// const imageData = lodArray[mipLevel];\n// if (this.device.isExternalImage(imageData)) {\n// this.texture.copyExternalImage({image: imageData, z, mipLevel, flipY: true});\n// } else if (this._isTextureImageData(imageData)) {\n// this.texture.copyImageData({data: imageData.data, z, mipLevel});\n// } else {\n// throw new Error('Unsupported 2D mip-level payload');\n// }\n// }\n// }\n\n// /** Normalize 2D layer payload into an array of mip-level items */\n// private _normalizeTexture2DData(data: Texture2DData): (TextureImageData | ExternalImage)[] {\n// return Array.isArray(data) ? data : [data];\n// }\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray, TextureFormat, ExternalImage} from '@luma.gl/core';\nimport {isExternalImage, getExternalImageSize} from '@luma.gl/core';\n\nexport type TextureImageSource = ExternalImage;\n\n/**\n * One mip level\n * Basic data structure is similar to `ImageData`\n * additional optional fields can describe compressed texture data.\n */\nexport type TextureImageData = {\n /** Preferred WebGPU style format string. */\n textureFormat?: TextureFormat;\n /** WebGPU style format string. Defaults to 'rgba8unorm' */\n format?: TextureFormat;\n /** Typed Array with the bytes of the image. @note beware row byte alignment requirements */\n data: TypedArray;\n /** Width of the image, in pixels, @note beware row byte alignment requirements */\n width: number;\n /** Height of the image, in rows */\n height: number;\n};\n\n/**\n * A single mip-level can be initialized by data or an ImageBitmap etc\n * @note in the WebGPU spec a mip-level is called a subresource\n */\nexport type TextureMipLevelData = TextureImageData | TextureImageSource;\n\n/**\n * Texture data for one image \"slice\" (which can consist of multiple miplevels)\n * Thus data for one slice be a single mip level or an array of miplevels\n * @note in the WebGPU spec each cross-section image in a 3D texture is called a \"slice\",\n * in a array texture each image in the array is called an array \"layer\"\n * luma.gl calls one image in a GPU texture a \"slice\" regardless of context.\n */\nexport type TextureSliceData = TextureMipLevelData | TextureMipLevelData[];\n\n/** Names of cube texture faces */\nexport type TextureCubeFace = '+X' | '-X' | '+Y' | '-Y' | '+Z' | '-Z';\n\n/** Array of cube texture faces. @note: index in array is the face index */\n// biome-ignore format: preserve layout\nexport const TEXTURE_CUBE_FACES = ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] as const satisfies readonly TextureCubeFace[];\n\n/** Map of cube texture face names to face indexes */\n// biome-ignore format: preserve layout\nexport const TEXTURE_CUBE_FACE_MAP = {'+X': 0, '-X': 1, '+Y': 2, '-Y': 3, '+Z': 4, '-Z': 5} as const satisfies Record<TextureCubeFace, number>;\n\n/** @todo - Define what data type is supported for 1D textures. TextureImageData with height = 1 */\nexport type Texture1DData = TextureSliceData;\n\n/** Texture data can be one or more mip levels */\nexport type Texture2DData = TextureSliceData;\n\n/** Texture data accepted when initializing a standalone 2D texture. */\ntype Texture2DDataSource = Texture2DData | TypedArray;\n\n/** 6 face textures */\nexport type TextureCubeData = Record<TextureCubeFace, TextureSliceData>;\n\n/** Array of textures */\nexport type Texture3DData = TextureSliceData[];\n\n/** Array of textures */\nexport type TextureArrayData = TextureSliceData[];\n\n/** Array of 6 face textures */\nexport type TextureCubeArrayData = Record<TextureCubeFace, TextureSliceData>[];\n\ntype TextureData =\n | Texture1DData\n | Texture3DData\n | TextureArrayData\n | TextureCubeArrayData\n | TextureCubeData;\n\n/** Sync data props */\nexport type TextureDataProps =\n | {dimension: '1d'; data: Texture1DData | null}\n | {dimension?: '2d'; data: Texture2DDataSource | null}\n | {dimension: '3d'; data: Texture3DData | null}\n | {dimension: '2d-array'; data: TextureArrayData | null}\n | {dimension: 'cube'; data: TextureCubeData | null}\n | {dimension: 'cube-array'; data: TextureCubeArrayData | null};\n\n/** Async data props */\nexport type TextureDataAsyncProps =\n | {dimension: '1d'; data?: Promise<Texture1DData> | Texture1DData | null}\n | {dimension?: '2d'; data?: Promise<Texture2DDataSource> | Texture2DDataSource | null}\n | {dimension: '3d'; data?: Promise<Texture3DData> | Texture3DData | null}\n | {dimension: '2d-array'; data?: Promise<TextureArrayData> | TextureArrayData | null}\n | {dimension: 'cube'; data?: Promise<TextureCubeData> | TextureCubeData | null}\n | {dimension: 'cube-array'; data?: Promise<TextureCubeArrayData> | TextureCubeArrayData | null};\n\n/** Describes data for one sub resource (one mip level of one slice (depth or array layer)) */\nexport type TextureSubresource = {\n /** slice (depth or array layer)) */\n z: number;\n /** mip level (0 - max mip levels) */\n mipLevel: number;\n} & (\n | {\n type: 'external-image';\n image: ExternalImage;\n /** @deprecated is this an appropriate place for this flag? */\n flipY?: boolean;\n }\n | {\n type: 'texture-data';\n data: TextureImageData;\n textureFormat?: TextureFormat;\n }\n);\n\n/** Check if texture data is a typed array */\nexport function isTextureSliceData(data: TextureData): data is TextureImageData {\n const typedArray = (data as TextureImageData)?.data;\n return ArrayBuffer.isView(typedArray);\n}\n\nexport function getFirstMipLevel(layer: TextureSliceData | null): TextureMipLevelData | null {\n if (!layer) return null;\n return Array.isArray(layer) ? (layer[0] ?? null) : layer;\n}\n\nexport function getTextureSizeFromData(\n props: TextureDataProps\n): {width: number; height: number} | null {\n const {dimension, data} = props;\n if (!data) {\n return null;\n }\n\n switch (dimension) {\n case '1d': {\n const mipLevel = getFirstMipLevel(data);\n if (!mipLevel) return null;\n const {width} = getTextureMipLevelSize(mipLevel);\n return {width, height: 1};\n }\n case '2d': {\n if (ArrayBuffer.isView(data)) return null;\n const mipLevel = getFirstMipLevel(data);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case '3d':\n case '2d-array': {\n if (!Array.isArray(data) || data.length === 0) return null;\n const mipLevel = getFirstMipLevel(data[0]);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case 'cube': {\n const face = (Object.keys(data)[0] as TextureCubeFace) ?? null;\n if (!face) return null;\n const faceData = (data as Record<TextureCubeFace, TextureSliceData>)[face];\n const mipLevel = getFirstMipLevel(faceData);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case 'cube-array': {\n if (!Array.isArray(data) || data.length === 0) return null;\n const firstCube = data[0];\n const face = (Object.keys(firstCube)[0] as TextureCubeFace) ?? null;\n if (!face) return null;\n const mipLevel = getFirstMipLevel(firstCube[face]);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n default:\n return null;\n }\n}\n\nfunction getTextureMipLevelSize(data: TextureMipLevelData): {width: number; height: number} {\n if (isExternalImage(data)) {\n return getExternalImageSize(data);\n }\n if (typeof data === 'object' && 'width' in data && 'height' in data) {\n return {width: data.width, height: data.height};\n }\n throw new Error('Unsupported mip-level data');\n}\n\n/** Type guard: is a mip-level `TextureImageData` (vs ExternalImage or bare typed array) */\nfunction isTextureImageData(data: unknown): data is TextureImageData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'data' in data &&\n 'width' in data &&\n 'height' in data\n );\n}\n\nfunction isTypedArrayMipLevelData(data: unknown): data is TypedArray {\n return ArrayBuffer.isView(data);\n}\n\nexport function resolveTextureImageFormat(data: TextureImageData): TextureFormat | undefined {\n const {textureFormat, format} = data;\n if (textureFormat && format && textureFormat !== format) {\n throw new Error(\n `Conflicting texture formats \"${textureFormat}\" and \"${format}\" provided for the same mip level`\n );\n }\n return textureFormat ?? format;\n}\n\n/** Resolve size for a single mip-level datum */\n// function getTextureMipLevelSizeFromData(data: TextureMipLevelData): {\n// width: number;\n// height: number;\n// } {\n// if (this.device.isExternalImage(data)) {\n// return this.device.getExternalImageSize(data);\n// }\n// if (this.isTextureImageData(data)) {\n// return {width: data.width, height: data.height};\n// }\n// // Fallback (should not happen with current types)\n// throw new Error('Unsupported mip-level data');\n// }\n\n/** Convert cube face label to depth index */\nexport function getCubeFaceIndex(face: TextureCubeFace): number {\n const idx = TEXTURE_CUBE_FACE_MAP[face];\n if (idx === undefined) throw new Error(`Invalid cube face: ${face}`);\n return idx;\n}\n\n/** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\nexport function getCubeArrayFaceIndex(cubeIndex: number, face: TextureCubeFace): number {\n return 6 * cubeIndex + getCubeFaceIndex(face);\n}\n\n// ------------------ Upload helpers ------------------\n\n/** Experimental: Set multiple mip levels (1D) */\nexport function getTexture1DSubresources(data: Texture1DData): TextureSubresource[] {\n // Not supported in WebGL; left explicit\n throw new Error('setTexture1DData not supported in WebGL.');\n // const subresources: TextureSubresource[] = [];\n // return subresources;\n}\n\n/** Normalize 2D layer payload into an array of mip-level items */\nfunction _normalizeTexture2DData(\n data: Texture2DDataSource\n): (TextureImageData | ExternalImage | TypedArray)[] {\n return Array.isArray(data) ? data : [data];\n}\n\n/** Experimental: Set multiple mip levels (2D), optionally at `z` (depth/array index) */\nexport function getTexture2DSubresources(\n slice: number,\n lodData: Texture2DDataSource,\n baseLevelSize?: {width: number; height: number},\n textureFormat?: TextureFormat\n): TextureSubresource[] {\n const lodArray = _normalizeTexture2DData(lodData);\n const z = slice;\n\n const subresources: TextureSubresource[] = [];\n\n for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) {\n const imageData = lodArray[mipLevel];\n if (isExternalImage(imageData)) {\n subresources.push({\n type: 'external-image',\n image: imageData,\n z,\n mipLevel\n });\n } else if (isTextureImageData(imageData)) {\n subresources.push({\n type: 'texture-data',\n data: imageData,\n textureFormat: resolveTextureImageFormat(imageData),\n z,\n mipLevel\n });\n } else if (isTypedArrayMipLevelData(imageData) && baseLevelSize) {\n subresources.push({\n type: 'texture-data',\n data: {\n data: imageData,\n width: Math.max(1, baseLevelSize.width >> mipLevel),\n height: Math.max(1, baseLevelSize.height >> mipLevel),\n ...(textureFormat ? {format: textureFormat} : {})\n },\n textureFormat,\n z,\n mipLevel\n });\n } else {\n throw new Error('Unsupported 2D mip-level payload');\n }\n }\n\n return subresources;\n}\n\n/** 3D: multiple depth slices, each may carry multiple mip levels */\nexport function getTexture3DSubresources(data: Texture3DData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (let depth = 0; depth < data.length; depth++) {\n subresources.push(...getTexture2DSubresources(depth, data[depth]));\n }\n return subresources;\n}\n\n/** 2D array: multiple layers, each may carry multiple mip levels */\nexport function getTextureArraySubresources(data: TextureArrayData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (let layer = 0; layer < data.length; layer++) {\n subresources.push(...getTexture2DSubresources(layer, data[layer]));\n }\n return subresources;\n}\n\n/** Cube: 6 faces, each may carry multiple mip levels */\nexport function getTextureCubeSubresources(data: TextureCubeData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (const [face, faceData] of Object.entries(data) as [TextureCubeFace, TextureSliceData][]) {\n const faceDepth = getCubeFaceIndex(face);\n subresources.push(...getTexture2DSubresources(faceDepth, faceData));\n }\n return subresources;\n}\n\n/** Cube array: multiple cubes (faces\u00D7layers), each face may carry multiple mips */\nexport function getTextureCubeArraySubresources(data: TextureCubeArrayData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n data.forEach((cubeData, cubeIndex) => {\n for (const [face, faceData] of Object.entries(cubeData)) {\n const faceDepth = getCubeArrayFaceIndex(cubeIndex, face as TextureCubeFace);\n subresources.push(...getTexture2DSubresources(faceDepth, faceData));\n }\n });\n return subresources;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, type CommandEncoder, Texture} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport {DynamicTexture} from '../dynamic-texture/dynamic-texture';\nimport {ClipSpace, ClipSpaceProps} from './clip-space';\n\nconst backgroundModule = {\n name: 'background',\n uniformTypes: {\n scale: 'vec2<f32>',\n flipY: 'i32'\n }\n} as const satisfies ShaderModule<{}, {scale: [number, number]; flipY: number}>;\n\nconst BACKGROUND_FS_WGSL = /* wgsl */ `\\\n@group(0) @binding(auto) var backgroundTexture: texture_2d<f32>;\n@group(0) @binding(auto) var backgroundTextureSampler: sampler;\nstruct backgroundUniforms {\n scale: vec2<f32>,\n flipY: i32,\n};\n@group(0) @binding(auto) var<uniform> background: backgroundUniforms;\n\nfn billboardTexture_getTextureUV(uv: vec2<f32>) -> vec2<f32> {\n let scale: vec2<f32> = background.scale;\n var position: vec2<f32> = (uv - vec2<f32>(0.5, 0.5)) / scale + vec2<f32>(0.5, 0.5);\n if (background.flipY != 0) {\n position.y = 1.0 - position.y;\n }\n return position;\n}\n\n@fragment\nfn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4<f32> {\n let position: vec2<f32> = billboardTexture_getTextureUV(inputs.uv);\n return textureSample(backgroundTexture, backgroundTextureSampler, position);\n}\n`;\n\nconst BACKGROUND_FS = /* glsl */ `\\\n#version 300 es\nprecision highp float;\n\nuniform sampler2D backgroundTexture;\n\nlayout(std140) uniform backgroundUniforms {\n vec2 scale;\n int flipY;\n} background;\n\nin vec2 coordinate;\nout vec4 fragColor;\n\nvec2 billboardTexture_getTextureUV(vec2 coord) {\n vec2 position = (coord - 0.5) / background.scale + 0.5;\n if (background.flipY != 0) {\n position.y = 1.0 - position.y;\n }\n return position;\n}\n\nvoid main(void) {\n vec2 position = billboardTexture_getTextureUV(coordinate);\n fragColor = texture(backgroundTexture, position);\n}\n`;\n\n/**\n * Props for a Model that renders a bitmap into the \"background\", i.e covering the screen\n */\nexport type BackgroundTextureModelProps = ClipSpaceProps & {\n /** id of this model */\n id?: string;\n /** The texture to render */\n backgroundTexture: Texture | DynamicTexture;\n /** If true, the texture is rendered into transparent areas of the screen only, i.e blended in where background alpha is small */\n blend?: boolean;\n /** If true, flip the sampled texture vertically before drawing. */\n flipY?: boolean;\n};\n\n/**\n * Model that renders a bitmap into the \"background\", i.e covering the screen\n */\nexport class BackgroundTextureModel extends ClipSpace {\n backgroundTexture: Texture = null!;\n flipY = false;\n\n constructor(device: Device, props: BackgroundTextureModelProps) {\n super(device, {\n ...props,\n id: props.id || 'background-texture-model',\n source: BACKGROUND_FS_WGSL,\n fs: BACKGROUND_FS,\n modules: [...(props.modules || []), backgroundModule],\n parameters: {\n depthWriteEnabled: false,\n ...(props.parameters || {}),\n ...(props.blend\n ? {\n blend: true,\n blendColorOperation: 'add',\n blendAlphaOperation: 'add',\n blendColorSrcFactor: 'one-minus-dst-alpha',\n blendColorDstFactor: 'one',\n blendAlphaSrcFactor: 'one-minus-dst-alpha',\n blendAlphaDstFactor: 'one'\n }\n : {})\n }\n });\n\n if (!props.backgroundTexture) {\n throw new Error('BackgroundTextureModel requires a backgroundTexture prop');\n }\n this.setProps(props);\n }\n\n /** Update the background texture */\n setProps(props: Partial<BackgroundTextureModelProps>): void {\n const {backgroundTexture} = props;\n if (props.flipY !== undefined) {\n this.flipY = props.flipY;\n if (this.backgroundTexture) {\n this.updateScale(this.backgroundTexture);\n }\n }\n\n if (backgroundTexture) {\n this.setBindings({backgroundTexture});\n\n if (backgroundTexture.isReady) {\n const texture =\n backgroundTexture instanceof DynamicTexture\n ? backgroundTexture.texture\n : backgroundTexture;\n this.backgroundTexture = texture;\n this.updateScale(texture);\n } else {\n backgroundTexture.ready.then(texture => {\n this.backgroundTexture = texture;\n this.updateScale(texture);\n });\n }\n }\n }\n\n override predraw(commandEncoder: CommandEncoder): void {\n // this.updateScale(this.backgroundTexture);\n super.predraw(commandEncoder);\n }\n\n updateScale(texture: Texture): void {\n if (!texture) {\n // Initial scale to avoid rendering issues before texture is loaded\n this.shaderInputs.setProps({background: {scale: [1, 1], flipY: 0}});\n return;\n }\n const [screenWidth, screenHeight] = this.device.getCanvasContext().getDrawingBufferSize();\n\n const textureWidth = texture.width;\n const textureHeight = texture.height;\n\n const screenAspect = screenWidth / screenHeight;\n const textureAspect = textureWidth / textureHeight;\n\n let scaleX = 1;\n let scaleY = 1;\n if (screenAspect > textureAspect) {\n scaleY = screenAspect / textureAspect;\n } else {\n scaleX = textureAspect / screenAspect;\n }\n\n this.shaderInputs.setProps({\n background: {scale: [scaleX, scaleY], flipY: this.flipY ? 1 : 0}\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\nexport type SphereGeometryProps = {\n id?: string;\n radius?: number;\n nlat?: number;\n nlong?: number;\n attributes?: any;\n};\n\n// Primitives inspired by TDL http://code.google.com/p/webglsamples/,\n// copyright 2011 Google Inc. new BSD License\n// (http://www.opensource.org/licenses/bsd-license.php).\nexport class SphereGeometry extends Geometry {\n constructor(props: SphereGeometryProps = {}) {\n const {id = uid('sphere-geometry')} = props;\n const {indices, attributes} = tesselateSphere(props);\n super({\n ...props,\n id,\n topology: 'triangle-list',\n indices,\n attributes: {...attributes, ...props.attributes}\n });\n }\n}\n\n/* eslint-disable max-statements, complexity */\nfunction tesselateSphere(props: SphereGeometryProps) {\n const {nlat = 10, nlong = 10} = props;\n\n const startLat = 0;\n const endLat = Math.PI;\n const latRange = endLat - startLat;\n const startLong = 0;\n const endLong = 2 * Math.PI;\n const longRange = endLong - startLong;\n const numVertices = (nlat + 1) * (nlong + 1);\n\n const radius = (n1: number, n2: number, n3: number, u: number, v: number) => props.radius || 1;\n\n const positions = new Float32Array(numVertices * 3);\n const normals = new Float32Array(numVertices * 3);\n const texCoords = new Float32Array(numVertices * 2);\n\n const IndexType = numVertices > 0xffff ? Uint32Array : Uint16Array;\n const indices = new IndexType(nlat * nlong * 6);\n\n // Create positions, normals and texCoords\n for (let y = 0; y <= nlat; y++) {\n for (let x = 0; x <= nlong; x++) {\n const u = x / nlong;\n const v = y / nlat;\n\n const index = x + y * (nlong + 1);\n const i2 = index * 2;\n const i3 = index * 3;\n\n const theta = longRange * u;\n const phi = latRange * v;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n const sinPhi = Math.sin(phi);\n const cosPhi = Math.cos(phi);\n const ux = cosTheta * sinPhi;\n const uy = cosPhi;\n const uz = sinTheta * sinPhi;\n\n const r = radius(ux, uy, uz, u, v);\n\n positions[i3 + 0] = r * ux;\n positions[i3 + 1] = r * uy;\n positions[i3 + 2] = r * uz;\n\n normals[i3 + 0] = ux;\n normals[i3 + 1] = uy;\n normals[i3 + 2] = uz;\n\n texCoords[i2 + 0] = u;\n texCoords[i2 + 1] = 1 - v;\n }\n }\n\n // Create indices\n const numVertsAround = nlong + 1;\n for (let x = 0; x < nlong; x++) {\n for (let y = 0; y < nlat; y++) {\n const index = (x * nlat + y) * 6;\n\n indices[index + 0] = y * numVertsAround + x;\n indices[index + 1] = y * numVertsAround + x + 1;\n indices[index + 2] = (y + 1) * numVertsAround + x;\n\n indices[index + 3] = (y + 1) * numVertsAround + x;\n indices[index + 4] = y * numVertsAround + x + 1;\n indices[index + 5] = (y + 1) * numVertsAround + x + 1;\n }\n }\n\n return {\n indices: {size: 1, value: indices},\n attributes: {\n POSITION: {size: 3, value: positions},\n NORMAL: {size: 3, value: normals},\n TEXCOORD_0: {size: 2, value: texCoords}\n }\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Buffer, Device, type RenderPass, type RenderPipelineParameters} from '@luma.gl/core';\nimport {Matrix4, type NumericArray} from '@math.gl/core';\nimport type {\n DirectionalLight,\n Light,\n PointLight,\n ShaderModule,\n SpotLight\n} from '@luma.gl/shadertools';\nimport {Model, type ModelProps} from '../model/model';\nimport {ShaderInputs} from '../shader-inputs';\nimport type {Geometry} from '../geometry/geometry';\n\nconst DEFAULT_POINT_LIGHT_RADIUS_FACTOR = 0.02;\nconst DEFAULT_SPOT_LIGHT_LENGTH_FACTOR = 0.12;\nconst DEFAULT_DIRECTIONAL_LIGHT_LENGTH_FACTOR = 0.15;\nconst DEFAULT_DIRECTIONAL_LIGHT_RADIUS_FACTOR = 0.2;\nconst DEFAULT_DIRECTION_FALLBACK: [number, number, number] = [0, 1, 0];\nconst DEFAULT_LIGHT_COLOR: [number, number, number] = [255, 255, 255];\nconst DEFAULT_MARKER_SCALE = 1;\nconst DIRECTIONAL_ANCHOR_DISTANCE_FACTOR = 0.35;\nconst LIGHT_COLOR_FACTOR = 255;\nconst MIN_SCENE_SCALE = 1;\nconst SPOTLIGHT_OUTER_CONE_EPSILON = 0.01;\n\nexport type LightModelBounds = [[number, number, number], [number, number, number]];\n\nexport type BaseLightModelProps = Omit<\n ModelProps,\n 'geometry' | 'modules' | 'shaderInputs' | 'source' | 'vs' | 'fs' | 'instanceCount'\n> & {\n lights: ReadonlyArray<Light>;\n viewMatrix: NumericArray;\n projectionMatrix: NumericArray;\n bounds?: LightModelBounds;\n markerScale?: number;\n};\n\nexport type PointLightModelProps = BaseLightModelProps & {\n pointLightRadius?: number;\n};\n\nexport type SpotLightModelProps = BaseLightModelProps & {\n spotLightLength?: number;\n};\n\nexport type DirectionalLightModelProps = BaseLightModelProps & {\n directionalLightLength?: number;\n};\n\ntype LightMarkerUniforms = {\n viewProjectionMatrix: Matrix4;\n};\n\nexport type LightMarkerInstanceData = {\n instanceCount: number;\n instancePositions: Float32Array;\n instanceDirections: Float32Array;\n instanceScales: Float32Array;\n instanceColors: Float32Array;\n};\n\ntype ManagedInstanceBuffers = Record<\n 'instancePosition' | 'instanceDirection' | 'instanceScale' | 'instanceColor',\n Buffer\n>;\n\ntype LightMarkerAnchorMode = 'centered' | 'apex';\n\ntype LightMarkerModelOptions<PropsT extends BaseLightModelProps> = {\n anchorMode: LightMarkerAnchorMode;\n buildInstanceData: (props: PropsT) => LightMarkerInstanceData;\n geometry: Geometry;\n idPrefix: string;\n sizePropNames: Array<keyof PropsT>;\n};\n\nconst LIGHT_MARKER_PARAMETERS: RenderPipelineParameters = {\n depthCompare: 'less-equal',\n depthWriteEnabled: false,\n cullMode: 'none'\n};\n\nconst INSTANCE_BUFFER_LAYOUT = [\n {name: 'instancePosition', format: 'float32x3', stepMode: 'instance'},\n {name: 'instanceDirection', format: 'float32x3', stepMode: 'instance'},\n {name: 'instanceScale', format: 'float32x3', stepMode: 'instance'},\n {name: 'instanceColor', format: 'float32x4', stepMode: 'instance'}\n] as const;\n\nconst lightMarker = {\n name: 'lightMarker',\n props: {} as LightMarkerUniforms,\n uniforms: {} as LightMarkerUniforms,\n uniformTypes: {\n viewProjectionMatrix: 'mat4x4<f32>'\n }\n} as const satisfies ShaderModule<LightMarkerUniforms, LightMarkerUniforms>;\n\nconst CENTERED_LOCAL_POSITION_WGSL = 'inputs.positions * inputs.instanceScale';\nconst APEX_LOCAL_POSITION_WGSL =\n 'vec3<f32>(inputs.positions.x * inputs.instanceScale.x, (inputs.positions.y - 0.5) * inputs.instanceScale.y, inputs.positions.z * inputs.instanceScale.z)';\nconst CENTERED_LOCAL_POSITION_GLSL = 'positions * instanceScale';\nconst APEX_LOCAL_POSITION_GLSL =\n 'vec3(positions.x * instanceScale.x, (positions.y - 0.5) * instanceScale.y, positions.z * instanceScale.z)';\n\nexport abstract class BaseLightModel<PropsT extends BaseLightModelProps> extends Model {\n protected lightModelProps: PropsT;\n protected _instanceData: LightMarkerInstanceData;\n protected _managedBuffers: ManagedInstanceBuffers;\n\n private readonly buildInstanceData: (props: PropsT) => LightMarkerInstanceData;\n private readonly sizePropNames: Array<keyof PropsT>;\n\n constructor(device: Device, props: PropsT, options: LightMarkerModelOptions<PropsT>) {\n const instanceData = options.buildInstanceData(props);\n const managedBuffers = createManagedInstanceBuffers(\n device,\n props.id || options.idPrefix,\n instanceData\n );\n const shaderInputs = new ShaderInputs<{\n lightMarker: typeof lightMarker.props;\n }>({lightMarker});\n shaderInputs.setProps({\n lightMarker: {viewProjectionMatrix: createViewProjectionMatrix(props)}\n });\n\n const {source, vs, fs} = getLightMarkerShaders(options.anchorMode);\n const modelProps: ModelProps = props;\n\n super(device, {\n ...modelProps,\n id: props.id || options.idPrefix,\n source,\n vs,\n fs,\n geometry: options.geometry,\n shaderInputs,\n bufferLayout: [...INSTANCE_BUFFER_LAYOUT],\n attributes: managedBuffers,\n instanceCount: instanceData.instanceCount,\n parameters: mergeLightMarkerParameters(props.parameters)\n });\n\n this.lightModelProps = props;\n this._instanceData = instanceData;\n this._managedBuffers = managedBuffers;\n this.buildInstanceData = options.buildInstanceData;\n this.sizePropNames = options.sizePropNames;\n }\n\n override destroy(): void {\n super.destroy();\n destroyManagedInstanceBuffers(this._managedBuffers);\n this._managedBuffers = {} as ManagedInstanceBuffers;\n }\n\n override draw(renderPass: RenderPass): boolean {\n if (this.instanceCount === 0) {\n return true;\n }\n return super.draw(renderPass);\n }\n\n setProps(props: Partial<PropsT>): void {\n this.lightModelProps = {...this.lightModelProps, ...props};\n\n if (props.parameters) {\n this.setParameters(mergeLightMarkerParameters(this.lightModelProps.parameters));\n }\n\n if ('viewMatrix' in props || 'projectionMatrix' in props) {\n this.shaderInputs.setProps({\n lightMarker: {viewProjectionMatrix: createViewProjectionMatrix(this.lightModelProps)}\n });\n this.setNeedsRedraw('lightMarker camera');\n }\n\n if (shouldRebuildInstanceData(props, this.sizePropNames)) {\n this.rebuildInstanceData();\n }\n }\n\n private rebuildInstanceData(): void {\n const nextInstanceData = this.buildInstanceData(this.lightModelProps);\n const nextManagedBuffers = createManagedInstanceBuffers(this.device, this.id, nextInstanceData);\n\n this.setAttributes(nextManagedBuffers);\n this.setInstanceCount(nextInstanceData.instanceCount);\n\n destroyManagedInstanceBuffers(this._managedBuffers);\n this._managedBuffers = nextManagedBuffers;\n this._instanceData = nextInstanceData;\n }\n}\n\nexport function buildPointLightInstanceData(props: PointLightModelProps): LightMarkerInstanceData {\n const pointLights = getPointLights(props.lights);\n const context = getLightMarkerContext(props);\n const pointLightRadius =\n props.pointLightRadius ??\n DEFAULT_POINT_LIGHT_RADIUS_FACTOR * context.sceneScale * context.markerScale;\n\n return createLightMarkerInstanceData(\n pointLights.length,\n (light, _index) => ({\n color: getDisplayColor(light),\n direction: DEFAULT_DIRECTION_FALLBACK,\n position: light.position,\n scale: [pointLightRadius, pointLightRadius, pointLightRadius]\n }),\n pointLights\n );\n}\n\nexport function buildSpotLightInstanceData(props: SpotLightModelProps): LightMarkerInstanceData {\n const spotLights = getSpotLights(props.lights);\n const context = getLightMarkerContext(props);\n const spotLightLength =\n props.spotLightLength ??\n DEFAULT_SPOT_LIGHT_LENGTH_FACTOR * context.sceneScale * context.markerScale;\n\n return createLightMarkerInstanceData(\n spotLights.length,\n (light, _index) => {\n const outerConeAngle = clamp(\n light.outerConeAngle ?? Math.PI / 4,\n 0,\n Math.PI / 2 - SPOTLIGHT_OUTER_CONE_EPSILON\n );\n const radius = Math.tan(outerConeAngle) * spotLightLength;\n\n return {\n color: getDisplayColor(light),\n direction: normalizeDirection(light.direction),\n position: light.position,\n scale: [radius, spotLightLength, radius]\n };\n },\n spotLights\n );\n}\n\nexport function buildDirectionalLightInstanceData(\n props: DirectionalLightModelProps\n): LightMarkerInstanceData {\n const directionalLights = getDirectionalLights(props.lights);\n const context = getLightMarkerContext(props);\n const directionalLightLength =\n props.directionalLightLength ??\n DEFAULT_DIRECTIONAL_LIGHT_LENGTH_FACTOR * context.sceneScale * context.markerScale;\n const directionalLightRadius = directionalLightLength * DEFAULT_DIRECTIONAL_LIGHT_RADIUS_FACTOR;\n\n return createLightMarkerInstanceData(\n directionalLights.length,\n (light, _index) => {\n const direction = normalizeDirection(light.direction);\n const position = [\n context.sceneCenter[0] -\n direction[0] * context.sceneScale * DIRECTIONAL_ANCHOR_DISTANCE_FACTOR,\n context.sceneCenter[1] -\n direction[1] * context.sceneScale * DIRECTIONAL_ANCHOR_DISTANCE_FACTOR,\n context.sceneCenter[2] -\n direction[2] * context.sceneScale * DIRECTIONAL_ANCHOR_DISTANCE_FACTOR\n ] as [number, number, number];\n\n return {\n color: getDisplayColor(light),\n direction,\n position,\n scale: [directionalLightRadius, directionalLightLength, directionalLightRadius]\n };\n },\n directionalLights\n );\n}\n\nexport function getPointLights(lights: ReadonlyArray<Light>): PointLight[] {\n return lights.filter((light): light is PointLight => light.type === 'point');\n}\n\nexport function getSpotLights(lights: ReadonlyArray<Light>): SpotLight[] {\n return lights.filter((light): light is SpotLight => light.type === 'spot');\n}\n\nexport function getDirectionalLights(lights: ReadonlyArray<Light>): DirectionalLight[] {\n return lights.filter((light): light is DirectionalLight => light.type === 'directional');\n}\n\nexport function getLightMarkerContext(props: BaseLightModelProps): {\n bounds: LightModelBounds;\n markerScale: number;\n sceneCenter: [number, number, number];\n sceneScale: number;\n} {\n const bounds = getSceneBounds(props.lights, props.bounds);\n const sceneCenter = [\n (bounds[0][0] + bounds[1][0]) / 2,\n (bounds[0][1] + bounds[1][1]) / 2,\n (bounds[0][2] + bounds[1][2]) / 2\n ] as [number, number, number];\n const sceneScale = Math.max(\n Math.hypot(\n bounds[1][0] - bounds[0][0],\n bounds[1][1] - bounds[0][1],\n bounds[1][2] - bounds[0][2]\n ),\n MIN_SCENE_SCALE\n );\n\n return {\n bounds,\n markerScale: Math.max(props.markerScale ?? DEFAULT_MARKER_SCALE, 0),\n sceneCenter,\n sceneScale\n };\n}\n\nexport function getDisplayColor(light: {\n color?: Readonly<[number, number, number]>;\n intensity?: number;\n}): [number, number, number, number] {\n const color = light.color || DEFAULT_LIGHT_COLOR;\n const intensity = Math.max(light.intensity ?? 1, 0);\n const brightness = clamp(0.35 + 0.3 * Math.log10(intensity + 1), 0.35, 1);\n\n return [\n clamp(color[0] / LIGHT_COLOR_FACTOR, 0, 1) * brightness,\n clamp(color[1] / LIGHT_COLOR_FACTOR, 0, 1) * brightness,\n clamp(color[2] / LIGHT_COLOR_FACTOR, 0, 1) * brightness,\n 1\n ];\n}\n\nexport function normalizeDirection(\n direction?: Readonly<[number, number, number]>\n): [number, number, number] {\n const [x, y, z] = direction || DEFAULT_DIRECTION_FALLBACK;\n const length = Math.hypot(x, y, z);\n if (length === 0) {\n return [...DEFAULT_DIRECTION_FALLBACK];\n }\n return [x / length, y / length, z / length];\n}\n\nfunction createLightMarkerInstanceData<TLight>(\n instanceCount: number,\n getInstance: (\n light: TLight,\n index: number\n ) => {\n color: [number, number, number, number];\n direction: [number, number, number];\n position: Readonly<NumericArray>;\n scale: [number, number, number];\n },\n lights: TLight[] = []\n): LightMarkerInstanceData {\n const instancePositions = new Float32Array(instanceCount * 3);\n const instanceDirections = new Float32Array(instanceCount * 3);\n const instanceScales = new Float32Array(instanceCount * 3);\n const instanceColors = new Float32Array(instanceCount * 4);\n\n for (const [index, light] of lights.entries()) {\n const instance = getInstance(light, index);\n instancePositions.set(instance.position, index * 3);\n instanceDirections.set(instance.direction, index * 3);\n instanceScales.set(instance.scale, index * 3);\n instanceColors.set(instance.color, index * 4);\n }\n\n return {\n instanceCount,\n instancePositions,\n instanceDirections,\n instanceScales,\n instanceColors\n };\n}\n\nfunction getSceneBounds(lights: ReadonlyArray<Light>, bounds?: LightModelBounds): LightModelBounds {\n if (bounds) {\n return cloneBounds(bounds);\n }\n\n const positions = [\n ...getPointLights(lights).map(light => light.position),\n ...getSpotLights(lights).map(light => light.position)\n ];\n\n if (positions.length === 0) {\n return [\n [-0.5, -0.5, -0.5],\n [0.5, 0.5, 0.5]\n ];\n }\n\n const minBounds: [number, number, number] = [...positions[0]] as [number, number, number];\n const maxBounds: [number, number, number] = [...positions[0]] as [number, number, number];\n\n for (const position of positions.slice(1)) {\n minBounds[0] = Math.min(minBounds[0], position[0]);\n minBounds[1] = Math.min(minBounds[1], position[1]);\n minBounds[2] = Math.min(minBounds[2], position[2]);\n\n maxBounds[0] = Math.max(maxBounds[0], position[0]);\n maxBounds[1] = Math.max(maxBounds[1], position[1]);\n maxBounds[2] = Math.max(maxBounds[2], position[2]);\n }\n\n return [minBounds, maxBounds];\n}\n\nfunction cloneBounds(bounds: LightModelBounds): LightModelBounds {\n return [[...bounds[0]] as [number, number, number], [...bounds[1]] as [number, number, number]];\n}\n\nfunction createManagedInstanceBuffers(\n device: Device,\n idPrefix: string,\n instanceData: LightMarkerInstanceData\n): ManagedInstanceBuffers {\n return {\n instancePosition: device.createBuffer({\n id: `${idPrefix}-instance-position`,\n data: getBufferDataOrPlaceholder(instanceData.instancePositions, 3)\n }),\n instanceDirection: device.createBuffer({\n id: `${idPrefix}-instance-direction`,\n data: getBufferDataOrPlaceholder(instanceData.instanceDirections, 3)\n }),\n instanceScale: device.createBuffer({\n id: `${idPrefix}-instance-scale`,\n data: getBufferDataOrPlaceholder(instanceData.instanceScales, 3)\n }),\n instanceColor: device.createBuffer({\n id: `${idPrefix}-instance-color`,\n data: getBufferDataOrPlaceholder(instanceData.instanceColors, 4)\n })\n };\n}\n\nfunction getBufferDataOrPlaceholder(data: Float32Array, size: number): Float32Array {\n return data.length > 0 ? data : new Float32Array(size);\n}\n\nfunction destroyManagedInstanceBuffers(managedBuffers: Partial<ManagedInstanceBuffers>): void {\n for (const buffer of Object.values(managedBuffers)) {\n buffer?.destroy();\n }\n}\n\nfunction createViewProjectionMatrix(\n props: Pick<BaseLightModelProps, 'projectionMatrix' | 'viewMatrix'>\n): Matrix4 {\n return new Matrix4(props.projectionMatrix).multiplyRight(props.viewMatrix);\n}\n\nfunction shouldRebuildInstanceData<PropsT extends BaseLightModelProps>(\n props: Partial<PropsT>,\n sizePropNames: Array<keyof PropsT>\n): boolean {\n if ('lights' in props || 'bounds' in props || 'markerScale' in props) {\n return true;\n }\n return sizePropNames.some(sizePropName => sizePropName in props);\n}\n\nfunction mergeLightMarkerParameters(\n parameters?: RenderPipelineParameters\n): RenderPipelineParameters {\n return {\n ...LIGHT_MARKER_PARAMETERS,\n ...(parameters || {})\n };\n}\n\nfunction getLightMarkerShaders(anchorMode: LightMarkerAnchorMode): {\n fs: string;\n source: string;\n vs: string;\n} {\n const localPositionWGSL =\n anchorMode === 'apex' ? APEX_LOCAL_POSITION_WGSL : CENTERED_LOCAL_POSITION_WGSL;\n const localPositionGLSL =\n anchorMode === 'apex' ? APEX_LOCAL_POSITION_GLSL : CENTERED_LOCAL_POSITION_GLSL;\n\n return {\n source: `\\\nstruct lightMarkerUniforms {\n viewProjectionMatrix: mat4x4<f32>,\n};\n\n@group(0) @binding(auto) var<uniform> lightMarker : lightMarkerUniforms;\n\nstruct VertexInputs {\n @location(0) positions : vec3<f32>,\n @location(1) instancePosition : vec3<f32>,\n @location(2) instanceDirection : vec3<f32>,\n @location(3) instanceScale : vec3<f32>,\n @location(4) instanceColor : vec4<f32>,\n};\n\nstruct FragmentInputs {\n @builtin(position) Position : vec4<f32>,\n @location(0) color : vec4<f32>,\n};\n\nfn lightMarker_rotate(localPosition: vec3<f32>, direction: vec3<f32>) -> vec3<f32> {\n let forward = normalize(direction);\n var helperAxis = vec3<f32>(0.0, 1.0, 0.0);\n if (abs(forward.y) > 0.999) {\n helperAxis = vec3<f32>(1.0, 0.0, 0.0);\n }\n\n let tangent = normalize(cross(helperAxis, forward));\n let bitangent = cross(forward, tangent);\n return tangent * localPosition.x + forward * localPosition.y + bitangent * localPosition.z;\n}\n\n@vertex\nfn vertexMain(inputs: VertexInputs) -> FragmentInputs {\n var outputs : FragmentInputs;\n let localPosition = ${localPositionWGSL};\n let worldPosition = inputs.instancePosition + lightMarker_rotate(localPosition, inputs.instanceDirection);\n outputs.Position = lightMarker.viewProjectionMatrix * vec4<f32>(worldPosition, 1.0);\n outputs.color = inputs.instanceColor;\n return outputs;\n}\n\n@fragment\nfn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4<f32> {\n return inputs.color;\n}\n`,\n vs: `\\\n#version 300 es\n\nin vec3 positions;\nin vec3 instancePosition;\nin vec3 instanceDirection;\nin vec3 instanceScale;\nin vec4 instanceColor;\n\nlayout(std140) uniform lightMarkerUniforms {\n mat4 viewProjectionMatrix;\n} lightMarker;\n\nout vec4 vColor;\n\nvec3 lightMarker_rotate(vec3 localPosition, vec3 direction) {\n vec3 forward = normalize(direction);\n vec3 helperAxis = abs(forward.y) > 0.999 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);\n vec3 tangent = normalize(cross(helperAxis, forward));\n vec3 bitangent = cross(forward, tangent);\n return tangent * localPosition.x + forward * localPosition.y + bitangent * localPosition.z;\n}\n\nvoid main(void) {\n vec3 localPosition = ${localPositionGLSL};\n vec3 worldPosition = instancePosition + lightMarker_rotate(localPosition, instanceDirection);\n gl_Position = lightMarker.viewProjectionMatrix * vec4(worldPosition, 1.0);\n vColor = instanceColor;\n}\n`,\n fs: `\\\n#version 300 es\nprecision highp float;\n\nin vec4 vColor;\nout vec4 fragColor;\n\nvoid main(void) {\n fragColor = vColor;\n}\n`\n };\n}\n\nfunction clamp(value: number, minValue: number, maxValue: number): number {\n return Math.min(maxValue, Math.max(minValue, value));\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '@luma.gl/core';\nimport {SphereGeometry} from '../geometries/sphere-geometry';\nimport {\n BaseLightModel,\n buildPointLightInstanceData,\n type PointLightModelProps\n} from './light-model-utils';\n\nconst POINT_LIGHT_GEOMETRY = new SphereGeometry({\n nlat: 8,\n nlong: 12,\n radius: 1\n});\n\nexport type {PointLightModelProps} from './light-model-utils';\n\nexport class PointLightModel extends BaseLightModel<PointLightModelProps> {\n constructor(device: Device, props: PointLightModelProps) {\n super(device, props, {\n anchorMode: 'centered',\n buildInstanceData: buildPointLightInstanceData,\n geometry: POINT_LIGHT_GEOMETRY,\n idPrefix: 'point-light-model',\n sizePropNames: ['pointLightRadius']\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\nconst INDEX_OFFSETS = {\n x: [2, 0, 1],\n y: [0, 1, 2],\n z: [1, 2, 0]\n};\n\nexport type TruncatedConeGeometryProps = {\n topRadius?: number;\n bottomRadius?: number;\n topCap?: boolean;\n bottomCap?: boolean;\n height?: number;\n nradial?: number;\n nvertical?: number;\n verticalAxis?: 'x' | 'y' | 'z';\n};\n\n/**\n * Primitives inspired by TDL http://code.google.com/p/webglsamples/,\n * copyright 2011 Google Inc. new BSD License\n * (http://www.opensource.org/licenses/bsd-license.php).\n */\nexport class TruncatedConeGeometry extends Geometry {\n constructor(props: TruncatedConeGeometryProps & {id?: string; attributes?: any} = {}) {\n const {id = uid('truncated-code-geometry')} = props;\n const {indices, attributes} = tesselateTruncatedCone(props);\n super({\n ...props,\n id,\n topology: 'triangle-list',\n indices,\n attributes: {\n POSITION: {size: 3, value: attributes.POSITION},\n NORMAL: {size: 3, value: attributes.NORMAL},\n TEXCOORD_0: {size: 2, value: attributes.TEXCOORD_0},\n ...props.attributes\n }\n });\n }\n}\n\n/* eslint-disable max-statements, complexity */\nfunction tesselateTruncatedCone(props: TruncatedConeGeometryProps = {}) {\n const {\n bottomRadius = 0,\n topRadius = 0,\n height = 1,\n nradial = 10,\n nvertical = 10,\n verticalAxis = 'y',\n topCap = false,\n bottomCap = false\n } = props;\n\n const extra = (topCap ? 2 : 0) + (bottomCap ? 2 : 0);\n const numVertices = (nradial + 1) * (nvertical + 1 + extra);\n\n const slant = Math.atan2(bottomRadius - topRadius, height);\n const msin = Math.sin;\n const mcos = Math.cos;\n const mpi = Math.PI;\n const cosSlant = mcos(slant);\n const sinSlant = msin(slant);\n const start = topCap ? -2 : 0;\n const end = nvertical + (bottomCap ? 2 : 0);\n const vertsAroundEdge = nradial + 1;\n\n const indices = new Uint16Array(nradial * (nvertical + extra) * 6);\n const indexOffset = INDEX_OFFSETS[verticalAxis];\n\n const positions = new Float32Array(numVertices * 3);\n const normals = new Float32Array(numVertices * 3);\n const texCoords = new Float32Array(numVertices * 2);\n\n let i3 = 0;\n let i2 = 0;\n for (let i = start; i <= end; i++) {\n let v = i / nvertical;\n let y = height * v;\n let ringRadius;\n\n if (i < 0) {\n y = 0;\n v = 1;\n ringRadius = bottomRadius;\n } else if (i > nvertical) {\n y = height;\n v = 1;\n ringRadius = topRadius;\n } else {\n ringRadius = bottomRadius + (topRadius - bottomRadius) * (i / nvertical);\n }\n if (i === -2 || i === nvertical + 2) {\n ringRadius = 0;\n v = 0;\n }\n y -= height / 2;\n for (let j = 0; j < vertsAroundEdge; j++) {\n const sin = msin((j * mpi * 2) / nradial);\n const cos = mcos((j * mpi * 2) / nradial);\n\n positions[i3 + indexOffset[0]] = sin * ringRadius;\n positions[i3 + indexOffset[1]] = y;\n positions[i3 + indexOffset[2]] = cos * ringRadius;\n\n normals[i3 + indexOffset[0]] = i < 0 || i > nvertical ? 0 : sin * cosSlant;\n normals[i3 + indexOffset[1]] = i < 0 ? -1 : i > nvertical ? 1 : sinSlant;\n normals[i3 + indexOffset[2]] = i < 0 || i > nvertical ? 0 : cos * cosSlant;\n\n texCoords[i2 + 0] = j / nradial;\n texCoords[i2 + 1] = v;\n\n i2 += 2;\n i3 += 3;\n }\n }\n\n for (let i = 0; i < nvertical + extra; i++) {\n for (let j = 0; j < nradial; j++) {\n const index = (i * nradial + j) * 6;\n indices[index + 0] = vertsAroundEdge * (i + 0) + 0 + j;\n indices[index + 1] = vertsAroundEdge * (i + 0) + 1 + j;\n indices[index + 2] = vertsAroundEdge * (i + 1) + 1 + j;\n indices[index + 3] = vertsAroundEdge * (i + 0) + 0 + j;\n indices[index + 4] = vertsAroundEdge * (i + 1) + 1 + j;\n indices[index + 5] = vertsAroundEdge * (i + 1) + 0 + j;\n }\n }\n\n return {\n indices,\n attributes: {\n POSITION: positions,\n NORMAL: normals,\n TEXCOORD_0: texCoords\n }\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TruncatedConeGeometryProps} from './truncated-cone-geometry';\nimport {TruncatedConeGeometry} from './truncated-cone-geometry';\nimport {uid} from '../utils/uid';\n\nexport type ConeGeometryProps = Omit<\n TruncatedConeGeometryProps,\n 'topRadius' | 'bottomRadius' | 'topCap' | 'bottomCap'\n> & {\n id?: string;\n radius?: number;\n cap?: boolean;\n attributes?: any;\n};\n\nexport class ConeGeometry extends TruncatedConeGeometry {\n constructor(props: ConeGeometryProps = {}) {\n const {id = uid('cone-geometry'), radius = 1, cap = true} = props;\n super({\n ...props,\n id,\n topRadius: 0,\n topCap: Boolean(cap),\n bottomCap: Boolean(cap),\n bottomRadius: radius\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '@luma.gl/core';\nimport {ConeGeometry} from '../geometries/cone-geometry';\nimport {\n BaseLightModel,\n buildSpotLightInstanceData,\n type SpotLightModelProps\n} from './light-model-utils';\n\nconst SPOT_LIGHT_GEOMETRY = new ConeGeometry({\n cap: true,\n nradial: 16,\n nvertical: 1,\n radius: 1\n});\n\nexport type {SpotLightModelProps} from './light-model-utils';\n\nexport class SpotLightModel extends BaseLightModel<SpotLightModelProps> {\n constructor(device: Device, props: SpotLightModelProps) {\n super(device, props, {\n anchorMode: 'apex',\n buildInstanceData: buildSpotLightInstanceData,\n geometry: SPOT_LIGHT_GEOMETRY,\n idPrefix: 'spot-light-model',\n sizePropNames: ['spotLightLength']\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '@luma.gl/core';\nimport {ConeGeometry} from '../geometries/cone-geometry';\nimport {\n BaseLightModel,\n buildDirectionalLightInstanceData,\n type DirectionalLightModelProps\n} from './light-model-utils';\n\nconst DIRECTIONAL_LIGHT_GEOMETRY = new ConeGeometry({\n cap: true,\n nradial: 12,\n nvertical: 1,\n radius: 1\n});\n\nexport type {DirectionalLightModelProps} from './light-model-utils';\n\nexport class DirectionalLightModel extends BaseLightModel<DirectionalLightModelProps> {\n constructor(device: Device, props: DirectionalLightModelProps) {\n super(device, props, {\n anchorMode: 'apex',\n buildInstanceData: buildDirectionalLightInstanceData,\n geometry: DIRECTIONAL_LIGHT_GEOMETRY,\n idPrefix: 'directional-light-model',\n sizePropNames: ['directionalLightLength']\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Vector3, Matrix4, NumericArray} from '@math.gl/core';\nimport {uid} from '../utils/uid';\n\nfunction assert(condition: boolean, message?: string): asserts condition {\n if (!condition) {\n throw new Error(message);\n }\n}\n\n/** Properties for creating a new Scenegraph */\nexport type ScenegraphNodeProps = {\n id?: string;\n /** whether to display the object at all */\n display?: boolean;\n matrix?: NumericArray;\n position?: NumericArray;\n rotation?: NumericArray;\n scale?: NumericArray;\n update?: boolean;\n};\n\nexport class ScenegraphNode {\n readonly id: string;\n matrix: Matrix4 = new Matrix4();\n\n display = true;\n position = new Vector3();\n rotation = new Vector3();\n scale = new Vector3(1, 1, 1);\n userData: Record<string, unknown> = {};\n\n props: ScenegraphNodeProps = {};\n\n constructor(props: ScenegraphNodeProps = {}) {\n const {id} = props;\n\n this.id = id || uid(this.constructor.name);\n\n this._setScenegraphNodeProps(props);\n }\n\n getBounds(): [number[], number[]] | null {\n return null;\n }\n\n destroy(): void {}\n\n /** @deprecated use .destroy() */\n delete(): void {\n this.destroy();\n }\n setProps(props: ScenegraphNodeProps): this {\n this._setScenegraphNodeProps(props);\n return this;\n }\n\n toString(): string {\n return `{type: ScenegraphNode, id: ${this.id})}`;\n }\n\n setPosition(position: any): this {\n assert(position.length === 3, 'setPosition requires vector argument');\n this.position = position;\n return this;\n }\n\n setRotation(rotation: any): this {\n assert(rotation.length === 3 || rotation.length === 4, 'setRotation requires vector argument');\n this.rotation = rotation;\n return this;\n }\n\n setScale(scale: any): this {\n assert(scale.length === 3, 'setScale requires vector argument');\n this.scale = scale;\n return this;\n }\n\n setMatrix(matrix: any, copyMatrix: boolean = true): void {\n if (copyMatrix) {\n this.matrix.copy(matrix);\n } else {\n this.matrix = matrix;\n }\n }\n\n setMatrixComponents(components: {\n position?: any;\n rotation?: any;\n scale?: any;\n update?: boolean;\n }): this {\n const {position, rotation, scale, update = true} = components;\n if (position) {\n this.setPosition(position);\n }\n if (rotation) {\n this.setRotation(rotation);\n }\n if (scale) {\n this.setScale(scale);\n }\n if (update) {\n this.updateMatrix();\n }\n return this;\n }\n\n updateMatrix(): this {\n this.matrix.identity();\n this.matrix.translate(this.position);\n if (this.rotation.length === 4) {\n const rotationMatrix = new Matrix4().fromQuaternion(this.rotation);\n this.matrix.multiplyRight(rotationMatrix);\n } else {\n this.matrix.rotateXYZ(this.rotation);\n }\n this.matrix.scale(this.scale);\n\n return this;\n }\n\n update({position, rotation, scale}: {position?: any; rotation?: any; scale?: any} = {}): this {\n if (position) {\n this.setPosition(position);\n }\n if (rotation) {\n this.setRotation(rotation);\n }\n if (scale) {\n this.setScale(scale);\n }\n\n this.updateMatrix();\n\n return this;\n }\n\n getCoordinateUniforms(\n viewMatrix: any,\n modelMatrix?: any\n ): {\n viewMatrix: any;\n modelMatrix: any;\n objectMatrix: any;\n worldMatrix: any;\n worldInverseMatrix: any;\n worldInverseTransposeMatrix: any;\n } {\n // TODO - solve multiple class problem\n // assert(viewMatrix instanceof Matrix4);\n // assert(viewMatrix);\n modelMatrix = modelMatrix || this.matrix;\n const worldMatrix = new Matrix4(viewMatrix).multiplyRight(modelMatrix);\n const worldInverse = worldMatrix.invert();\n const worldInverseTranspose = worldInverse.transpose();\n\n return {\n viewMatrix,\n modelMatrix,\n objectMatrix: modelMatrix,\n worldMatrix,\n worldInverseMatrix: worldInverse,\n worldInverseTransposeMatrix: worldInverseTranspose\n };\n }\n\n // TODO - copied code, not yet vetted\n /*\n transform() {\n if (!this.parent) {\n this.endPosition.set(this.position);\n this.endRotation.set(this.rotation);\n this.endScale.set(this.scale);\n } else {\n const parent = this.parent;\n this.endPosition.set(this.position.add(parent.endPosition));\n this.endRotation.set(this.rotation.add(parent.endRotation));\n this.endScale.set(this.scale.add(parent.endScale));\n }\n\n const ch = this.children;\n for (let i = 0; i < ch.length; ++i) {\n ch[i].transform();\n }\n\n return this;\n }\n */\n\n _setScenegraphNodeProps(props: ScenegraphNodeProps): void {\n // if ('display' in props) {\n // this.display = props.display;\n // }\n\n if (props?.position) {\n this.setPosition(props.position);\n }\n if (props?.rotation) {\n this.setRotation(props.rotation);\n }\n if (props?.scale) {\n this.setScale(props.scale);\n }\n\n this.updateMatrix();\n\n // Matrix overwrites other props\n if (props?.matrix) {\n this.setMatrix(props.matrix);\n }\n\n Object.assign(this.props, props);\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport type {NumericArray} from '@math.gl/core';\nimport {log} from '@luma.gl/core';\nimport {ScenegraphNode, ScenegraphNodeProps} from './scenegraph-node';\nimport {\n areScenegraphBoundsDefined,\n expandScenegraphBounds,\n makeEmptyScenegraphBounds\n} from './scenegraph-bounds';\nimport type {ScenegraphBounds} from './scenegraph-bounds';\n\nexport type GroupNodeProps = ScenegraphNodeProps & {\n children?: ScenegraphNode[];\n};\n\n/** Camera-relative ordering options for a flattened scenegraph traversal. */\nexport type DepthSortedTraversalOptions = {\n viewMatrix: NumericArray;\n worldMatrix?: NumericArray;\n order?: 'back-to-front' | 'front-to-back';\n};\n\n/** Model transform, local aggregate bounds, and positive camera depth for one visited node. */\nexport type DepthSortedTraversalContext = {\n worldMatrix: Matrix4;\n bounds: [number[], number[]] | null;\n depth: number;\n};\n\nexport class GroupNode extends ScenegraphNode {\n children: ScenegraphNode[];\n\n constructor(children: ScenegraphNode[]);\n constructor(props?: GroupNodeProps);\n\n constructor(props: ScenegraphNode[] | GroupNodeProps = {}) {\n props = Array.isArray(props) ? {children: props} : props;\n const {children = []} = props;\n log.assert(\n children.every(child => child instanceof ScenegraphNode),\n 'every child must an instance of ScenegraphNode'\n );\n super(props);\n this.children = children;\n }\n\n override getBounds(): ScenegraphBounds | null {\n const result = makeEmptyScenegraphBounds();\n\n this.traverse((node, {worldMatrix}) => {\n const bounds = node.getBounds();\n if (!bounds) {\n return;\n }\n const nodeWorldMatrix = new Matrix4(worldMatrix).multiplyRight(node.matrix);\n expandScenegraphBounds(result, bounds, nodeWorldMatrix);\n });\n return areScenegraphBoundsDefined(result) ? result : null;\n }\n\n override destroy(): void {\n this.children.forEach(child => child.destroy());\n this.removeAll();\n super.destroy();\n }\n\n // Unpacks arrays and nested arrays of children\n add(...children: (ScenegraphNode | ScenegraphNode[])[]): this {\n for (const child of children) {\n if (Array.isArray(child)) {\n this.add(...child);\n } else {\n this.children.push(child);\n }\n }\n return this;\n }\n\n remove(child: ScenegraphNode): this {\n const children = this.children;\n const indexOf = children.indexOf(child);\n if (indexOf > -1) {\n children.splice(indexOf, 1);\n }\n return this;\n }\n\n removeAll(): this {\n this.children = [];\n return this;\n }\n\n traverse(\n visitor: (node: ScenegraphNode, context: {worldMatrix: Matrix4}) => void,\n {worldMatrix = new Matrix4()} = {}\n ) {\n const modelMatrix = new Matrix4(worldMatrix).multiplyRight(this.matrix);\n\n for (const child of this.children) {\n if (child instanceof GroupNode) {\n child.traverse(visitor, {worldMatrix: modelMatrix});\n } else {\n visitor(child, {worldMatrix: modelMatrix});\n }\n }\n }\n\n /** Visits leaf nodes ordered by the camera-space centers of their aggregate bounds. */\n traverseDepthSorted(\n visitor: (node: ScenegraphNode, context: DepthSortedTraversalContext) => void,\n {viewMatrix, worldMatrix = new Matrix4(), order = 'back-to-front'}: DepthSortedTraversalOptions\n ): void {\n const cameraMatrix = new Matrix4(viewMatrix);\n const nodes: {node: ScenegraphNode; context: DepthSortedTraversalContext; index: number}[] = [];\n\n this.traverse(\n (node, context) => {\n const bounds = node.getBounds();\n const center = bounds\n ? new Vector3(bounds[0]).add(bounds[1]).divide([2, 2, 2])\n : new Vector3();\n const nodeWorldMatrix = new Matrix4(context.worldMatrix).multiplyRight(node.matrix);\n nodeWorldMatrix.transformAsPoint(center, center);\n cameraMatrix.transformAsPoint(center, center);\n nodes.push({\n node,\n context: {worldMatrix: nodeWorldMatrix, bounds, depth: -center[2]},\n index: nodes.length\n });\n },\n {worldMatrix: new Matrix4(worldMatrix)}\n );\n\n const direction = order === 'back-to-front' ? -1 : 1;\n nodes.sort(\n (first, second) =>\n direction * (first.context.depth - second.context.depth) || first.index - second.index\n );\n\n for (const {node, context} of nodes) {\n visitor(node, context);\n }\n }\n\n preorderTraversal(\n visitor: (node: ScenegraphNode, context: {worldMatrix: Matrix4}) => void,\n {worldMatrix = new Matrix4()} = {}\n ) {\n const modelMatrix = new Matrix4(worldMatrix).multiplyRight(this.matrix);\n visitor(this, {worldMatrix: modelMatrix});\n\n for (const child of this.children) {\n if (child instanceof GroupNode) {\n child.preorderTraversal(visitor, {worldMatrix: modelMatrix});\n } else {\n visitor(child, {worldMatrix: modelMatrix});\n }\n }\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport type {NumericArray} from '@math.gl/core';\n\n/** Axis-aligned bounds in a scenegraph node's local coordinate system. */\nexport type ScenegraphBounds = [[number, number, number], [number, number, number]];\n\nexport function makeEmptyScenegraphBounds(): ScenegraphBounds {\n return [\n [Infinity, Infinity, Infinity],\n [-Infinity, -Infinity, -Infinity]\n ];\n}\n\nexport function expandScenegraphBounds(\n targetBounds: ScenegraphBounds,\n sourceBounds: [number[], number[]],\n transform: NumericArray\n): void {\n const transformMatrix = new Matrix4(transform);\n\n for (let cornerIndex = 0; cornerIndex < 8; cornerIndex++) {\n const corner = new Vector3(\n sourceBounds[cornerIndex & 0b001 ? 1 : 0][0],\n sourceBounds[cornerIndex & 0b010 ? 1 : 0][1],\n sourceBounds[cornerIndex & 0b100 ? 1 : 0][2]\n );\n transformMatrix.transformAsPoint(corner, corner);\n\n for (let componentIndex = 0; componentIndex < 3; componentIndex++) {\n targetBounds[0][componentIndex] = Math.min(\n targetBounds[0][componentIndex],\n corner[componentIndex]\n );\n targetBounds[1][componentIndex] = Math.max(\n targetBounds[1][componentIndex],\n corner[componentIndex]\n );\n }\n }\n}\n\nexport function areScenegraphBoundsDefined(bounds: ScenegraphBounds): boolean {\n return Number.isFinite(bounds[0][0]);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {RenderPass} from '@luma.gl/core';\nimport type {NumericArray} from '@math.gl/core';\nimport {ScenegraphNode, ScenegraphNodeProps} from './scenegraph-node';\nimport {\n areScenegraphBoundsDefined,\n expandScenegraphBounds,\n makeEmptyScenegraphBounds\n} from './scenegraph-bounds';\nimport type {ScenegraphBounds} from './scenegraph-bounds';\nimport {Model} from '../model/model';\n\nexport type ModelNodeProps = ScenegraphNodeProps & {\n model: Model;\n managedResources?: any[];\n /** Bounds of one model instance before instance and node transforms. */\n bounds?: ScenegraphBounds;\n /** Optional per-instance transforms used to calculate aggregate local bounds. */\n instanceMatrices?: readonly NumericArray[];\n};\n\nexport class ModelNode extends ScenegraphNode {\n readonly model: Model;\n readonly instanceMatrices: readonly NumericArray[] | null;\n bounds: ScenegraphBounds | null = null;\n managedResources: any[];\n\n // TODO - is this used? override callbacks to make sure we call them with this\n // onBeforeRender = null;\n // onAfterRender = null;\n // AfterRender = null;\n\n constructor(props: ModelNodeProps) {\n super(props);\n\n // Create new Model or used supplied Model\n this.model = props.model;\n this.managedResources = props.managedResources || [];\n this.instanceMatrices = props.instanceMatrices || null;\n this.bounds = props.bounds\n ? this.instanceMatrices\n ? getInstancedScenegraphBounds(props.bounds, this.instanceMatrices)\n : props.bounds\n : null;\n this.setProps(props);\n }\n\n override destroy(): void {\n if (this.model) {\n this.model.destroy();\n // @ts-expect-error\n this.model = null;\n }\n this.managedResources.forEach(resource => resource.destroy());\n this.managedResources = [];\n }\n\n override getBounds(): [number[], number[]] | null {\n return this.bounds;\n }\n\n // Expose model methods\n draw(renderPass: RenderPass) {\n // Return value indicates if something was actually drawn\n return this.model.draw(renderPass);\n }\n}\n\nfunction getInstancedScenegraphBounds(\n bounds: ScenegraphBounds,\n instanceMatrices: readonly NumericArray[]\n): ScenegraphBounds | null {\n const instancedBounds = makeEmptyScenegraphBounds();\n\n for (const instanceMatrix of instanceMatrices) {\n expandScenegraphBounds(instancedBounds, bounds, instanceMatrix);\n }\n\n return areScenegraphBoundsDefined(instancedBounds) ? instancedBounds : null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n// import type {GeometryType} from '../geometry/geometry-type';\n\nexport type CubeGeometryProps = {\n id?: string;\n indices?: boolean;\n attributes?: any;\n};\n\nexport class CubeGeometry extends Geometry {\n constructor(props: CubeGeometryProps = {}) {\n const {id = uid('cube-geometry'), indices = true} = props;\n super(\n indices\n ? {\n ...props,\n id,\n topology: 'triangle-list',\n indices: {size: 1, value: CUBE_INDICES},\n attributes: {...ATTRIBUTES, ...props.attributes}\n }\n : {\n ...props,\n id,\n topology: 'triangle-list',\n indices: undefined,\n attributes: {...NON_INDEXED_ATTRIBUTES, ...props.attributes}\n }\n );\n }\n}\n\n// biome-ignore format: preserve layout\nconst CUBE_INDICES = new Uint16Array([\n 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13,\n 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23\n]);\n\n// biome-ignore format: preserve layout\nconst CUBE_POSITIONS = new Float32Array([\n -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1,\n -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1,\n -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1,\n -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1,\n 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1,\n -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1\n]);\n\n// TODO - could be Uint8\n// biome-ignore format: preserve layout\nconst CUBE_NORMALS = new Float32Array([\n // Front face\n 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,\n // Back face\n 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1,\n // Top face\n 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,\n // Bottom face\n 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,\n // Right face\n 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,\n // Left face\n -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0\n]);\n\n// biome-ignore format: preserve layout\nconst CUBE_TEX_COORDS = new Float32Array([\n // Front face\n 0, 0, 1, 0, 1, 1, 0, 1,\n // Back face\n 1, 0, 1, 1, 0, 1, 0, 0,\n // Top face\n 0, 1, 0, 0, 1, 0, 1, 1,\n // Bottom face\n 1, 1, 0, 1, 0, 0, 1, 0,\n // Right face\n 1, 0, 1, 1, 0, 1, 0, 0,\n // Left face\n 0, 0, 1, 0, 1, 1, 0, 1\n]);\n\n// biome-ignore format: preserve layout\nconst CUBE_FACE_INDICES = new Uint32Array([\n 0, 0, 0, 0,\n 1, 1, 1, 1,\n 2, 2, 2, 2,\n 3, 3, 3, 3,\n 4, 4, 4, 4,\n 5, 5, 5, 5\n]);\n\n// float4 position\n// biome-ignore format: preserve layout\nexport const CUBE_NON_INDEXED_POSITIONS = new Float32Array([\n 1, -1, 1,\n -1, -1, 1,\n -1, -1, -1,\n 1, -1, -1,\n 1, -1, 1,\n -1, -1, -1,\n\n 1, 1, 1,\n 1, -1, 1,\n 1, -1, -1,\n 1, 1, -1,\n 1, 1, 1,\n 1, -1, -1,\n\n -1, 1, 1,\n 1, 1, 1,\n 1, 1, -1,\n -1, 1, -1,\n -1, 1, 1,\n 1, 1, -1,\n\n -1, -1, 1,\n -1, 1, 1,\n -1, 1, -1,\n -1, -1, -1,\n -1, -1, 1,\n -1, 1, -1,\n\n 1, 1, 1,\n -1, 1, 1,\n -1, -1, 1,\n -1, -1, 1,\n 1, -1, 1,\n 1, 1, 1,\n\n 1, -1, -1,\n -1, -1, -1,\n -1, 1, -1,\n 1, 1, -1,\n 1, -1, -1,\n -1, 1, -1,\n]);\n\n// float2 uv,\n// biome-ignore format: preserve layout\nexport const CUBE_NON_INDEXED_TEX_COORDS = new Float32Array([\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 0, 0,\n 1, 0,\n 1, 1,\n\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n]);\n\n// float4 color\n// biome-ignore format: preserve layout\nexport const CUBE_NON_INDEXED_COLORS = new Float32Array([\n 1, 0, 1, 1,\n 0, 0, 1, 1,\n 0, 0, 0, 1,\n 1, 0, 0, 1,\n 1, 0, 1, 1,\n 0, 0, 0, 1,\n\n 1, 1, 1, 1,\n 1, 0, 1, 1,\n 1, 0, 0, 1,\n 1, 1, 0, 1,\n 1, 1, 1, 1,\n 1, 0, 0, 1,\n\n 0, 1, 1, 1,\n 1, 1, 1, 1,\n 1, 1, 0, 1,\n 0, 1, 0, 1,\n 0, 1, 1, 1,\n 1, 1, 0, 1,\n\n 0, 0, 1, 1,\n 0, 1, 1, 1,\n 0, 1, 0, 1,\n 0, 0, 0, 1,\n 0, 0, 1, 1,\n 0, 1, 0, 1,\n\n 1, 1, 1, 1,\n 0, 1, 1, 1,\n 0, 0, 1, 1,\n 0, 0, 1, 1,\n 1, 0, 1, 1,\n 1, 1, 1, 1,\n\n 1, 0, 0, 1,\n 0, 0, 0, 1,\n 0, 1, 0, 1,\n 1, 1, 0, 1,\n 1, 0, 0, 1,\n 0, 1, 0, 1,\n]);\n\n// biome-ignore format: preserve layout\nexport const CUBE_NON_INDEXED_FACE_INDICES = new Uint32Array([\n 3, 3, 3, 3, 3, 3,\n 4, 4, 4, 4, 4, 4,\n 2, 2, 2, 2, 2, 2,\n 5, 5, 5, 5, 5, 5,\n 0, 0, 0, 0, 0, 0,\n 1, 1, 1, 1, 1, 1\n]);\n\nconst ATTRIBUTES = {\n POSITION: {size: 3, value: CUBE_POSITIONS},\n NORMAL: {size: 3, value: CUBE_NORMALS},\n TEXCOORD_0: {size: 2, value: CUBE_TEX_COORDS},\n faceIndex: {size: 1, value: CUBE_FACE_INDICES}\n};\n\nconst NON_INDEXED_ATTRIBUTES = {\n POSITION: {size: 3, value: CUBE_NON_INDEXED_POSITIONS},\n // NORMAL: {size: 3, value: CUBE_NON_INDEXED_NORMALS},\n TEXCOORD_0: {size: 2, value: CUBE_NON_INDEXED_TEX_COORDS},\n COLOR_0: {size: 3, value: CUBE_NON_INDEXED_COLORS},\n faceIndex: {size: 1, value: CUBE_NON_INDEXED_FACE_INDICES}\n};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TruncatedConeGeometryProps} from './truncated-cone-geometry';\nimport {TruncatedConeGeometry} from './truncated-cone-geometry';\nimport {uid} from '../utils/uid';\n\nexport type CylinderGeometryProps = Omit<\n TruncatedConeGeometryProps,\n 'topRadius' | 'bottomRadius'\n> & {\n id?: string;\n radius?: number;\n attributes?: any;\n};\n\nexport class CylinderGeometry extends TruncatedConeGeometry {\n constructor(props: CylinderGeometryProps = {}) {\n const {id = uid('cylinder-geometry'), radius = 1} = props;\n super({\n ...props,\n id,\n bottomRadius: radius,\n topRadius: radius\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Vector3} from '@math.gl/core';\nimport {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\n/* eslint-disable comma-spacing, max-statements, complexity */\n\nconst ICO_POSITIONS = [-1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, -1, 0, 1, 0, 0];\nconst ICO_INDICES = [3, 4, 5, 3, 5, 1, 3, 1, 0, 3, 0, 4, 4, 0, 2, 4, 2, 5, 2, 0, 1, 5, 2, 1];\n\nexport type IcoSphereGeometryProps = {\n id?: string;\n radius?: number;\n iterations?: number;\n attributes?: any;\n};\n\nexport class IcoSphereGeometry extends Geometry {\n constructor(props: IcoSphereGeometryProps = {}) {\n const {id = uid('ico-sphere-geometry')} = props;\n const {indices, attributes} = tesselateIcosaHedron(props);\n super({\n ...props,\n id,\n topology: 'triangle-list',\n indices,\n attributes: {...attributes, ...props.attributes}\n });\n }\n}\n\nfunction tesselateIcosaHedron(props: IcoSphereGeometryProps) {\n const {iterations = 0} = props;\n\n const PI = Math.PI;\n const PI2 = PI * 2;\n\n const positions = [...ICO_POSITIONS];\n let indices = [...ICO_INDICES];\n\n positions.push();\n indices.push();\n\n const getMiddlePoint = (() => {\n const pointMemo: Record<string, number> = {};\n\n return (i1: number, i2: number) => {\n i1 *= 3;\n i2 *= 3;\n const mini = i1 < i2 ? i1 : i2;\n const maxi = i1 > i2 ? i1 : i2;\n const key = `${mini}|${maxi}`;\n\n if (key in pointMemo) {\n return pointMemo[key];\n }\n\n const x1 = positions[i1];\n const y1 = positions[i1 + 1];\n const z1 = positions[i1 + 2];\n const x2 = positions[i2];\n const y2 = positions[i2 + 1];\n const z2 = positions[i2 + 2];\n let xm = (x1 + x2) / 2;\n let ym = (y1 + y2) / 2;\n let zm = (z1 + z2) / 2;\n const len = Math.sqrt(xm * xm + ym * ym + zm * zm);\n\n xm /= len;\n ym /= len;\n zm /= len;\n\n positions.push(xm, ym, zm);\n\n const pointIndex = positions.length / 3 - 1;\n pointMemo[key] = pointIndex;\n return pointIndex;\n };\n })();\n\n for (let i = 0; i < iterations; i++) {\n const indices2: number[] = [];\n for (let j = 0; j < indices.length; j += 3) {\n const a = getMiddlePoint(indices[j + 0], indices[j + 1]);\n const b = getMiddlePoint(indices[j + 1], indices[j + 2]);\n const c = getMiddlePoint(indices[j + 2], indices[j + 0]);\n\n indices2.push(c, indices[j + 0], a, a, indices[j + 1], b, b, indices[j + 2], c, a, b, c);\n }\n indices = indices2;\n }\n\n // Calculate texCoords and normals\n const normals = new Array(positions.length);\n const texCoords = new Array((positions.length / 3) * 2);\n\n const l = indices.length;\n for (let i = l - 3; i >= 0; i -= 3) {\n const i1 = indices[i + 0];\n const i2 = indices[i + 1];\n const i3 = indices[i + 2];\n const in1 = i1 * 3;\n const in2 = i2 * 3;\n const in3 = i3 * 3;\n const iu1 = i1 * 2;\n const iu2 = i2 * 2;\n const iu3 = i3 * 2;\n const x1 = positions[in1 + 0];\n const y1 = positions[in1 + 1];\n const z1 = positions[in1 + 2];\n const theta1 = Math.acos(z1 / Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1));\n const phi1 = Math.atan2(y1, x1) + PI;\n const v1 = theta1 / PI;\n const u1 = 1 - phi1 / PI2;\n const x2 = positions[in2 + 0];\n const y2 = positions[in2 + 1];\n const z2 = positions[in2 + 2];\n const theta2 = Math.acos(z2 / Math.sqrt(x2 * x2 + y2 * y2 + z2 * z2));\n const phi2 = Math.atan2(y2, x2) + PI;\n const v2 = theta2 / PI;\n const u2 = 1 - phi2 / PI2;\n const x3 = positions[in3 + 0];\n const y3 = positions[in3 + 1];\n const z3 = positions[in3 + 2];\n const theta3 = Math.acos(z3 / Math.sqrt(x3 * x3 + y3 * y3 + z3 * z3));\n const phi3 = Math.atan2(y3, x3) + PI;\n const v3 = theta3 / PI;\n const u3 = 1 - phi3 / PI2;\n const vec1 = [x3 - x2, y3 - y2, z3 - z2];\n const vec2 = [x1 - x2, y1 - y2, z1 - z2];\n const normal = new Vector3(vec1).cross(vec2).normalize();\n let newIndex;\n\n if (\n (u1 === 0 || u2 === 0 || u3 === 0) &&\n (u1 === 0 || u1 > 0.5) &&\n (u2 === 0 || u2 > 0.5) &&\n (u3 === 0 || u3 > 0.5)\n ) {\n positions.push(positions[in1 + 0], positions[in1 + 1], positions[in1 + 2]);\n newIndex = positions.length / 3 - 1;\n indices.push(newIndex);\n texCoords[newIndex * 2 + 0] = 1;\n texCoords[newIndex * 2 + 1] = v1;\n normals[newIndex * 3 + 0] = normal.x;\n normals[newIndex * 3 + 1] = normal.y;\n normals[newIndex * 3 + 2] = normal.z;\n\n positions.push(positions[in2 + 0], positions[in2 + 1], positions[in2 + 2]);\n newIndex = positions.length / 3 - 1;\n indices.push(newIndex);\n texCoords[newIndex * 2 + 0] = 1;\n texCoords[newIndex * 2 + 1] = v2;\n normals[newIndex * 3 + 0] = normal.x;\n normals[newIndex * 3 + 1] = normal.y;\n normals[newIndex * 3 + 2] = normal.z;\n\n positions.push(positions[in3 + 0], positions[in3 + 1], positions[in3 + 2]);\n newIndex = positions.length / 3 - 1;\n indices.push(newIndex);\n texCoords[newIndex * 2 + 0] = 1;\n texCoords[newIndex * 2 + 1] = v3;\n normals[newIndex * 3 + 0] = normal.x;\n normals[newIndex * 3 + 1] = normal.y;\n normals[newIndex * 3 + 2] = normal.z;\n }\n\n normals[in1 + 0] = normals[in2 + 0] = normals[in3 + 0] = normal.x;\n normals[in1 + 1] = normals[in2 + 1] = normals[in3 + 1] = normal.y;\n normals[in1 + 2] = normals[in2 + 2] = normals[in3 + 2] = normal.z;\n\n texCoords[iu1 + 0] = u1;\n texCoords[iu1 + 1] = v1;\n\n texCoords[iu2 + 0] = u2;\n texCoords[iu2 + 1] = v2;\n\n texCoords[iu3 + 0] = u3;\n texCoords[iu3 + 1] = v3;\n }\n\n return {\n indices: {size: 1, value: new Uint16Array(indices)},\n attributes: {\n POSITION: {size: 3, value: new Float32Array(positions)},\n NORMAL: {size: 3, value: new Float32Array(normals)},\n TEXCOORD_0: {size: 2, value: new Float32Array(texCoords)}\n }\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geometry} from '../geometry/geometry';\nimport {unpackIndexedGeometry} from '../geometry/geometry-utils';\nimport {uid} from '../utils/uid';\n\nexport type PlaneGeometryProps = {\n id?: string;\n radius?: number;\n attributes?: any;\n type?: 'x,y' | 'x,z' | 'y,z';\n offset?: number;\n flipCull?: boolean;\n unpack?: boolean;\n xlen?: number;\n ylen?: number;\n zlen?: number;\n nx?: number;\n ny?: number;\n nz?: number;\n};\n\n// Primitives inspired by TDL http://code.google.com/p/webglsamples/,\n// copyright 2011 Google Inc. new BSD License\n// (http://www.opensource.org/licenses/bsd-license.php).\nexport class PlaneGeometry extends Geometry {\n constructor(props: PlaneGeometryProps = {}) {\n const {id = uid('plane-geometry')} = props;\n\n const {indices, attributes} = tesselatePlane(props);\n super({\n ...props,\n id,\n topology: 'triangle-list',\n indices,\n attributes: {...attributes, ...props.attributes}\n });\n }\n}\n\n/* eslint-disable complexity, max-statements */\nfunction tesselatePlane(props: any) {\n const {type = 'x,y', offset = 0, flipCull = false, unpack = false} = props;\n\n const coords = type.split(',');\n // width, height\n let c1len = props[`${coords[0]}len`] || 1;\n const c2len = props[`${coords[1]}len`] || 1;\n // subdivisionsWidth, subdivisionsDepth\n const subdivisions1 = props[`n${coords[0]}`] || 1;\n const subdivisions2 = props[`n${coords[1]}`] || 1;\n const numVertices = (subdivisions1 + 1) * (subdivisions2 + 1);\n\n const positions = new Float32Array(numVertices * 3);\n const normals = new Float32Array(numVertices * 3);\n const texCoords = new Float32Array(numVertices * 2);\n\n if (flipCull) {\n c1len = -c1len;\n }\n\n let i2 = 0;\n let i3 = 0;\n for (let z = 0; z <= subdivisions2; z++) {\n for (let x = 0; x <= subdivisions1; x++) {\n const u = x / subdivisions1;\n const v = z / subdivisions2;\n texCoords[i2 + 0] = flipCull ? 1 - u : u;\n texCoords[i2 + 1] = v;\n\n switch (type) {\n case 'x,y':\n positions[i3 + 0] = c1len * u - c1len * 0.5;\n positions[i3 + 1] = c2len * v - c2len * 0.5;\n positions[i3 + 2] = offset;\n\n normals[i3 + 0] = 0;\n normals[i3 + 1] = 0;\n normals[i3 + 2] = flipCull ? 1 : -1;\n break;\n\n case 'x,z':\n positions[i3 + 0] = c1len * u - c1len * 0.5;\n positions[i3 + 1] = offset;\n positions[i3 + 2] = c2len * v - c2len * 0.5;\n\n normals[i3 + 0] = 0;\n normals[i3 + 1] = flipCull ? 1 : -1;\n normals[i3 + 2] = 0;\n break;\n\n case 'y,z':\n positions[i3 + 0] = offset;\n positions[i3 + 1] = c1len * u - c1len * 0.5;\n positions[i3 + 2] = c2len * v - c2len * 0.5;\n\n normals[i3 + 0] = flipCull ? 1 : -1;\n normals[i3 + 1] = 0;\n normals[i3 + 2] = 0;\n break;\n\n default:\n throw new Error('PlaneGeometry: unknown type');\n }\n\n i2 += 2;\n i3 += 3;\n }\n }\n\n const numVertsAcross = subdivisions1 + 1;\n const indices = new Uint16Array(subdivisions1 * subdivisions2 * 6);\n\n for (let z = 0; z < subdivisions2; z++) {\n for (let x = 0; x < subdivisions1; x++) {\n const index = (z * subdivisions1 + x) * 6;\n // Make triangle 1 of quad.\n indices[index + 0] = (z + 0) * numVertsAcross + x;\n indices[index + 1] = (z + 1) * numVertsAcross + x;\n indices[index + 2] = (z + 0) * numVertsAcross + x + 1;\n\n // Make triangle 2 of quad.\n indices[index + 3] = (z + 1) * numVertsAcross + x;\n indices[index + 4] = (z + 1) * numVertsAcross + x + 1;\n indices[index + 5] = (z + 0) * numVertsAcross + x + 1;\n }\n }\n\n const geometry = {\n indices: {size: 1, value: indices},\n attributes: {\n POSITION: {size: 3, value: positions},\n NORMAL: {size: 3, value: normals},\n TEXCOORD_0: {size: 2, value: texCoords}\n }\n };\n\n // Optionally, unpack indexed geometry\n return unpack ? unpackIndexedGeometry(geometry) : geometry;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Creates a deterministic pseudorandom number generator */\nexport function makeRandomGenerator(): () => number {\n let s = 1;\n let c = 1;\n return () => {\n s = Math.sin(c * 17.23);\n c = Math.cos(s * 27.92);\n return fract(Math.abs(s * c) * 1432.71);\n };\n}\n\nfunction fract(n: number): number {\n return n - Math.floor(n);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nlet pathPrefix = '';\n\n/**\n * Set a relative path prefix\n */\nexport function setPathPrefix(prefix: string) {\n pathPrefix = prefix;\n}\n\n/** @internal */\nexport function _resolveLoadFileUrl(url: string): string {\n return isAbsoluteLoadFileUrl(url) ? url : pathPrefix + url;\n}\n\n/**\n * Loads ImageBitmap asynchronously. Respects setPathPrefix.\n * image.crossOrigin can be set via opts.crossOrigin, default to 'anonymous'\n * @returns a promise tracking the load\n */\nexport async function loadImageBitmap(\n url: string,\n opts?: {crossOrigin?: string} & ImageBitmapOptions\n): Promise<ImageBitmap> {\n const image = new Image();\n const resolvedUrl = _resolveLoadFileUrl(url);\n image.crossOrigin = opts?.crossOrigin || 'anonymous';\n image.src = resolvedUrl;\n\n try {\n await image.decode();\n } catch (error) {\n throw createImageBitmapLoadError('decode', resolvedUrl, error);\n }\n\n try {\n return opts ? await createImageBitmap(image, opts) : await createImageBitmap(image);\n } catch (error) {\n throw createImageBitmapLoadError('create', resolvedUrl, error);\n }\n}\n\n/**\n * Loads image asynchronously. Respects setPathPrefix.\n * image.crossOrigin can be set via opts.crossOrigin, default to 'anonymous'\n * @returns a promise tracking the load\n * @deprecated Use `loadImageBitmap()` unless you are supporting old versions of Safari.\n */\nexport async function loadImage(\n url: string,\n opts?: {crossOrigin?: string}\n): Promise<HTMLImageElement> {\n return await new Promise((resolve, reject) => {\n try {\n const image = new Image();\n const resolvedUrl = _resolveLoadFileUrl(url);\n image.onload = () => resolve(image);\n image.onerror = () => reject(new Error(`Could not load image ${resolvedUrl}.`));\n image.crossOrigin = opts?.crossOrigin || 'anonymous';\n image.src = resolvedUrl;\n } catch (error) {\n reject(error);\n }\n });\n}\n\nfunction createImageBitmapLoadError(\n phase: 'decode' | 'create',\n resolvedUrl: string,\n error: unknown\n): Error {\n const reason = error instanceof Error ? error.message : String(error);\n const message =\n phase === 'decode'\n ? `Could not decode source image \"${resolvedUrl}\": ${reason}`\n : `Could not create ImageBitmap from decoded image \"${resolvedUrl}\": ${reason}`;\n return new Error(message, {cause: error});\n}\nfunction isAbsoluteLoadFileUrl(url: string): boolean {\n return url.startsWith('/') || /^[a-z][a-z\\d+\\-.]*:/i.test(url);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, ExternalTexture, ResourceProps, Sampler, SamplerProps} from '@luma.gl/core';\nimport {Texture, assert} from '@luma.gl/core';\nimport {uid} from '../utils/uid';\nimport type {TextureBindingLayout, TextureBindingSource} from './texture-binding-source';\n\n/** Properties for a live video binding source. */\nexport type VideoTextureProps = Pick<ResourceProps, 'id'> & {\n /** Caller-owned live video source followed by this binding source. */\n source: HTMLVideoElement | VideoFrame;\n /** Color space requested for copied or imported video data. */\n colorSpace?: 'srgb';\n /** Default sampler used by copied and native external bindings. */\n sampler?: Sampler | SamplerProps;\n};\n\n/**\n * Live video binding source.\n *\n * GLSL `sampler2D` and WGSL `texture_2d` bindings resolve to copied luma textures.\n * WGSL `texture_external` bindings resolve to native WebGPU external textures.\n */\nexport class VideoTexture implements TextureBindingSource {\n /** Device used to create copied and native external texture bindings. */\n readonly device: Device;\n /** Stable resource identifier used in loading and debug messages. */\n readonly id: string;\n\n /** Whether this video binding source has been destroyed. */\n destroyed = false;\n /** Monotonic binding generation advanced when concrete draw bindings may need recreation. */\n generation = 0;\n\n private _source: HTMLVideoElement | VideoFrame;\n private _colorSpace: 'srgb';\n private _sampler: Sampler | SamplerProps;\n private _isReady = false;\n private _updateTimestamp: number;\n private _sourceVersion = 0;\n private _sourceFrameToken: unknown = null;\n private _texture: Texture | null = null;\n private _textureFrameToken: unknown = undefined;\n private _externalTexture: ExternalTexture | null = null;\n\n /** Current caller-owned live video source. */\n get source(): HTMLVideoElement | VideoFrame {\n return this._source;\n }\n\n /** Whether the current source exposes dimensions and a current frame. */\n get isReady(): boolean {\n this._observeSource();\n return this._isReady;\n }\n\n /** Device timestamp of the most recent source content or binding identity update. */\n get updateTimestamp(): number {\n this._observeSource();\n return this._updateTimestamp;\n }\n\n /** Resource label used by debug output. */\n get [Symbol.toStringTag]() {\n return 'VideoTexture';\n }\n\n /** Formats the current source dimensions and readiness for debug output. */\n toString(): string {\n const size = getVideoTextureSourceSize(this._source);\n return `VideoTexture:\"${this.id}\":${size.width}x${size.height}px:(${this._isReady ? 'ready' : 'loading...'})`;\n }\n\n /**\n * Creates a live video binding source.\n * @param device Device that resolves copied or native external bindings.\n * @param props Live video source and copied texture options.\n */\n constructor(device: Device, props: VideoTextureProps) {\n // Error: VideoTexture source must be an HTMLVideoElement or VideoFrame.\n assert(isHTMLVideoElementSource(props?.source) || isVideoFrameSource(props?.source));\n\n this.device = device;\n this.id = props.id || uid('video-texture');\n this._source = props.source;\n this._colorSpace = props.colorSpace ?? 'srgb';\n this._sampler = props.sampler ?? {};\n this._updateTimestamp = this.device.incrementTimestamp();\n\n this.setSource(props.source);\n }\n\n /**\n * Replaces the caller-owned video source and invalidates resolved bindings.\n * @param source Next caller-owned video source to follow.\n */\n setSource(source: HTMLVideoElement | VideoFrame): void {\n // Error: VideoTexture source must be an HTMLVideoElement or VideoFrame.\n assert(isHTMLVideoElementSource(source) || isVideoFrameSource(source));\n\n this._destroyExternalTexture();\n this._source = source;\n this._sourceVersion++;\n this._sourceFrameToken = null;\n this._textureFrameToken = undefined;\n this._observeSource();\n this._touchGeneration();\n }\n\n /**\n * Resolves one reflected shader texture slot for the current video frame.\n * @param bindingLayout Reflected `texture` or `external-texture` shader slot.\n * @returns A copied texture, native external texture, or `null` while unavailable.\n */\n resolveTextureBinding(bindingLayout: TextureBindingLayout): Texture | ExternalTexture | null {\n this._observeSource();\n if (!this._isReady || this.destroyed) {\n return null;\n }\n\n if (bindingLayout.type === 'external-texture' && this.device.type === 'webgpu') {\n return this._createNativeExternalTexture();\n }\n\n return this._resolveCopiedTexture();\n }\n\n /**\n * Replaces the default sampler used by copied and native external bindings.\n * @param sampler Sampler instance or sampler properties to use for future resolutions.\n */\n setSampler(sampler: Sampler | SamplerProps): void {\n this._sampler = sampler;\n this._texture?.setSampler(sampler);\n this._externalTexture?.setSampler?.(sampler);\n this._touchGeneration();\n }\n\n /** Releases owned copied/external bindings without closing the caller-owned source. */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this._destroyExternalTexture();\n this._texture?.destroy();\n this._texture = null;\n this._textureFrameToken = undefined;\n this._isReady = false;\n this.destroyed = true;\n this._touchGeneration();\n }\n\n /**\n * Resolves and uploads the copied texture variant for the current source frame.\n * @returns Copied texture containing the current observed frame.\n */\n private _resolveCopiedTexture(): Texture {\n const texture = this._getOrCreateCopiedTexture();\n if (!Object.is(this._textureFrameToken, this._sourceFrameToken)) {\n // A copy failure usually means that the video is not ready or CORS-accessible, or that the\n // caller closed the current VideoFrame before draw binding resolution completed.\n texture.copyExternalImage({\n image: this._source,\n colorSpace: this._colorSpace\n });\n this._textureFrameToken = this._sourceFrameToken;\n }\n return texture;\n }\n\n /**\n * Returns an existing size-compatible copied texture or creates one lazily.\n * @returns Copied texture allocated for the current source dimensions.\n */\n private _getOrCreateCopiedTexture(): Texture {\n const size = this._getResolvedSize();\n const currentTexture = this._texture;\n if (\n currentTexture &&\n currentTexture.width === size.width &&\n currentTexture.height === size.height\n ) {\n return currentTexture;\n }\n\n currentTexture?.destroy();\n\n const texture = this.device.createTexture({\n id: `${this.id}-texture`,\n width: size.width,\n height: size.height,\n format: 'rgba8unorm',\n usage: Texture.SAMPLE | Texture.COPY_DST,\n mipLevels: 1,\n sampler: this._sampler\n });\n this._texture = texture;\n this._textureFrameToken = undefined;\n this._touchGeneration();\n return texture;\n }\n\n /**\n * Acquires one native WebGPU external texture binding.\n * @returns Fresh acquired external texture.\n */\n private _createNativeExternalTexture(): ExternalTexture {\n // A WebGPU external-texture slot cannot accept a copied Texture fallback. Callers that need\n // the portable copied path must declare texture_2d<f32> in the shader instead.\n this._destroyExternalTexture();\n this._externalTexture = this.device.createExternalTexture({\n id: `${this.id}-external`,\n source: this._source,\n colorSpace: this._colorSpace,\n sampler: this._sampler\n });\n this.generation++;\n return this._externalTexture;\n }\n\n /** Releases the current acquired external texture wrapper. */\n private _destroyExternalTexture(): void {\n this._externalTexture?.destroy();\n this._externalTexture = null;\n }\n\n /**\n * Resolves current copied texture dimensions.\n * @returns Positive dimensions for the current source frame.\n */\n private _getResolvedSize(): {width: number; height: number} {\n const size = getVideoTextureSourceSize(this._source);\n // Error: VideoTexture source has no current frame size.\n assert(size.width > 0 && size.height > 0);\n return size;\n }\n\n /** Observes current source readiness and frame identity before binding resolution. */\n private _observeSource(): void {\n if (this.destroyed) {\n return;\n }\n\n const isReady = isVideoTextureSourceReady(this._source);\n if (isReady !== this._isReady) {\n this._isReady = isReady;\n this._touch();\n }\n\n if (!isReady) {\n return;\n }\n\n const frameToken = getVideoTextureSourceFrameToken(this._source, this._sourceVersion);\n if (!Object.is(frameToken, this._sourceFrameToken)) {\n this._sourceFrameToken = frameToken;\n this._touch();\n }\n }\n\n /** Advances the device timestamp after source content or readiness changes. */\n private _touch(): void {\n this._updateTimestamp = this.device.incrementTimestamp();\n }\n\n /** Advances binding generation and timestamp after binding identity can change. */\n private _touchGeneration(): void {\n this.generation++;\n this._touch();\n }\n}\n\n/** Returns whether a video source exposes HTML video element playback state. */\nfunction isHTMLVideoElementSource(source: unknown): source is HTMLVideoElement {\n if (!source || typeof source !== 'object') {\n return false;\n }\n\n return (\n (typeof HTMLVideoElement !== 'undefined' && source instanceof HTMLVideoElement) ||\n ('videoWidth' in source &&\n 'videoHeight' in source &&\n 'readyState' in source &&\n 'currentTime' in source)\n );\n}\n\n/** Returns whether a video source exposes VideoFrame dimensions and timestamp. */\nfunction isVideoFrameSource(source: unknown): source is VideoFrame {\n if (!source || typeof source !== 'object') {\n return false;\n }\n\n return (\n (typeof VideoFrame !== 'undefined' && source instanceof VideoFrame) ||\n ('displayWidth' in source &&\n 'displayHeight' in source &&\n 'timestamp' in source &&\n !('videoWidth' in source))\n );\n}\n\n/** Returns whether a video source exposes dimensions and a current sampleable frame. */\nfunction isVideoTextureSourceReady(source: HTMLVideoElement | VideoFrame): boolean {\n const size = getVideoTextureSourceSize(source);\n if (size.width <= 0 || size.height <= 0) {\n return false;\n }\n return isHTMLVideoElementSource(source) ? source.readyState >= 2 : true;\n}\n\n/** Returns current sampleable source dimensions. */\nfunction getVideoTextureSourceSize(source: HTMLVideoElement | VideoFrame): {\n width: number;\n height: number;\n} {\n if (isHTMLVideoElementSource(source)) {\n return {width: source.videoWidth, height: source.videoHeight};\n }\n return {width: source.displayWidth, height: source.displayHeight};\n}\n\n/** Returns the source token used to detect video frame replacement or advancement. */\nfunction getVideoTextureSourceFrameToken(\n source: HTMLVideoElement | VideoFrame,\n sourceVersion: number\n): unknown {\n if (isHTMLVideoElementSource(source)) {\n return `${sourceVersion}:${source.currentTime}:${source.videoWidth}x${source.videoHeight}`;\n }\n return `${sourceVersion}:${source.timestamp}:${source.displayWidth}x${source.displayHeight}`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CommandEncoder, TextureFormatColor} from '@luma.gl/core';\nimport {Device, Framebuffer, RenderPass, Texture} from '@luma.gl/core';\nimport type {\n ShaderPass,\n ShaderPassInputSource,\n ShaderPassPipeline,\n ShaderPassRenderTarget\n} from '@luma.gl/shadertools';\nimport {initializeShaderModule} from '@luma.gl/shadertools';\nimport {ShaderInputs} from '../shader-inputs';\nimport {DynamicTexture} from '../dynamic-texture/dynamic-texture';\nimport type {TextureBindingSource} from '../dynamic-texture/texture-binding-source';\nimport {ClipSpace} from '../models/clip-space';\nimport {SwapFramebuffers} from '../compute/swap';\nimport {BackgroundTextureModel} from '../models/billboard-texture-model';\n\nimport {getFragmentShaderForRenderPass} from './get-fragment-shader';\nimport {textureTransform} from './texture-transform-module';\n\ntype ShaderPassLike = ShaderPass | ShaderPassPipeline;\ntype ShaderSubPass = NonNullable<ShaderPass['passes']>[0];\n\ntype EffectiveSubPass = {\n ownerName: string;\n shaderPass: ShaderPass;\n subPassRenderer: SubPassRenderer;\n inputs?: Partial<Record<string, ShaderPassInputSource<string>>>;\n output?: 'previous' | string;\n uniforms?: Record<string, unknown>;\n};\n\ntype ManagedRenderTarget = {\n name: string;\n spec: ShaderPassRenderTarget;\n texture: Texture;\n framebuffer: Framebuffer;\n historyTexture?: Texture;\n historyFramebuffer?: Framebuffer;\n historyInitialized: boolean;\n writtenThisFrame: boolean;\n};\n\nconst RESERVED_RENDER_TARGET_NAMES = new Set(['original', 'previous']);\n\n/** Construction props for {@link ShaderPassRenderer}. */\nexport type ShaderPassRendererProps = {\n /** List of ShaderPasses or ShaderPassPipelines to apply to the sourceTexture */\n shaderPasses: ShaderPassLike[];\n /** Optional typed ShaderInputs object for setting uniforms */\n shaderInputs?: ShaderInputs;\n /** Format of the shared previous-chain textures. Defaults to the canvas-preferred format. */\n colorFormat?: TextureFormatColor;\n /** Flip source and presentation sampling vertically. Defaults to true on WebGPU. */\n flipY?: boolean;\n};\n\n/** Source texture accepted by {@link ShaderPassRenderer}. */\nexport type ShaderPassSourceTexture = DynamicTexture | Texture;\n/** Binding accepted by shader pass inputs, including deferred texture binding sources. */\nexport type ShaderPassBinding = Binding | TextureBindingSource;\n\n/** Per-frame inputs accepted by {@link ShaderPassRenderer}. */\nexport type ShaderPassRendererRenderOptions = {\n sourceTexture: ShaderPassSourceTexture;\n uniforms?: Record<string, Record<string, unknown>>;\n bindings?: Record<string, ShaderPassBinding>;\n /** Invalidates all persistent render targets before rendering this frame. */\n resetHistory?: boolean;\n};\n\n/**\n * Runs one or more shader passes against a source texture.\n *\n * The renderer owns:\n * - a shared ping-pong pair for the logical `previous` chain\n * - any named render targets declared by `ShaderPassPipeline`\n * - a fullscreen model used both to seed the chain and to present to the screen\n *\n * Per-draw `uniforms` and `bindings` passed to `renderToTexture()` or `renderToScreen()` are\n * merged on top of the renderer's `shaderInputs`, which lets callers reuse one renderer instance\n * while varying pass inputs frame to frame.\n */\nexport class ShaderPassRenderer {\n device: Device;\n shaderInputs: ShaderInputs;\n passRenderers: PassRenderer[];\n swapFramebuffers: SwapFramebuffers;\n textureModel: BackgroundTextureModel;\n\n constructor(device: Device, props: ShaderPassRendererProps) {\n this.device = device;\n\n const executableShaderPasses = getExecutableShaderPasses(props.shaderPasses);\n executableShaderPasses.map(shaderPass => initializeShaderModule(shaderPass));\n\n const modules = executableShaderPasses.reduce(\n (object, shaderPass) => ({...object, [shaderPass.name]: shaderPass}),\n {}\n );\n this.shaderInputs = props.shaderInputs || new ShaderInputs(modules);\n\n const size = device.getCanvasContext().getDrawingBufferSize();\n this.swapFramebuffers = new SwapFramebuffers(device, {\n colorAttachments: [props.colorFormat || device.preferredColorFormat],\n width: size[0],\n height: size[1]\n });\n\n this.textureModel = new BackgroundTextureModel(device, {\n backgroundTexture: this.swapFramebuffers.current.colorAttachments[0].texture,\n flipY: props.flipY ?? device.type === 'webgpu'\n });\n\n const flipY = props.flipY ?? device.type === 'webgpu';\n this.passRenderers = props.shaderPasses.map(\n shaderPass => new PassRenderer(device, shaderPass, this.shaderInputs, flipY)\n );\n }\n\n /** Destroys resources created by this ShaderPassRenderer */\n destroy() {\n for (const passRenderer of this.passRenderers) {\n passRenderer.destroy();\n }\n this.swapFramebuffers.destroy();\n this.textureModel.destroy();\n }\n\n resize(size?: [width: number, height: number]): void {\n size ||= this.device.getCanvasContext().getDrawingBufferSize();\n this.swapFramebuffers.resize({width: size[0], height: size[1]});\n for (const passRenderer of this.passRenderers) {\n passRenderer.resize(size);\n }\n }\n\n /** Invalidates persistent pipeline targets without destroying their allocations. */\n resetHistory(): void {\n for (const passRenderer of this.passRenderers) {\n passRenderer.resetHistory();\n }\n }\n\n renderToScreen(options: ShaderPassRendererRenderOptions): boolean {\n return this.encodeToScreen(this.device.commandEncoder, options);\n }\n\n /**\n * Records the shader-pass chain and presentation into a caller-owned command encoder.\n * The encoder must belong to this renderer's device and have no active pass. This method does\n * not finish or submit the encoder.\n */\n encodeToScreen(\n commandEncoder: CommandEncoder,\n options: ShaderPassRendererRenderOptions\n ): boolean {\n const outputTexture = this.encodeToTexture(commandEncoder, options);\n if (!outputTexture) {\n return false;\n }\n\n const framebuffer = this.device\n .getDefaultCanvasContext()\n .getCurrentFramebuffer({depthStencilFormat: false});\n // Prepare fullscreen presentation bindings before opening the render pass so WebGPU\n // uploads stay on the parent command encoder rather than the active render pass encoder.\n this.textureModel.setProps({backgroundTexture: outputTexture});\n this.textureModel.predraw(commandEncoder);\n const renderPass = commandEncoder.beginRenderPass({\n id: 'shader-pass-renderer-to-screen',\n framebuffer,\n clearDepth: false\n });\n this.textureModel.draw(renderPass);\n renderPass.end();\n return true;\n }\n\n /** Runs the shaderPasses in sequence on the sourceTexture and returns a texture with the results.\n * @returns null if the the sourceTexture has not yet been loaded\n */\n renderToTexture(options: ShaderPassRendererRenderOptions): Texture | null {\n return this.encodeToTexture(this.device.commandEncoder, options);\n }\n\n /**\n * Records the shader-pass chain into a caller-owned command encoder.\n * The encoder must belong to this renderer's device and have no active pass. This method does\n * not finish or submit the encoder.\n */\n encodeToTexture(\n commandEncoder: CommandEncoder,\n options: ShaderPassRendererRenderOptions\n ): Texture | null {\n if (commandEncoder.device !== this.device) {\n throw new Error('ShaderPassRenderer command encoder must belong to the renderer device');\n }\n const {sourceTexture} = options;\n if (sourceTexture instanceof DynamicTexture && !sourceTexture.isReady) {\n return null;\n }\n const originalTexture =\n sourceTexture instanceof DynamicTexture ? sourceTexture.texture : sourceTexture;\n\n if (this.passRenderers.length === 0) {\n return originalTexture;\n }\n\n if (options.resetHistory) {\n this.resetHistory();\n }\n\n // Seed the first shared framebuffer with the original source. This normalizes the starting\n // point for later passes so `previous` always refers to a drawing-buffer-sized texture.\n this.textureModel.setProps({backgroundTexture: originalTexture});\n // The seed draw updates fullscreen bind groups, so it must be prepared before the\n // render pass begins to avoid command-encoder locking errors on WebGPU.\n this.textureModel.predraw(commandEncoder);\n\n const sourceFramebuffer = getSeedFramebuffer(this.swapFramebuffers, originalTexture);\n const seedRenderPass = commandEncoder.beginRenderPass({\n id: 'shader-pass-renderer-seed-source',\n framebuffer: sourceFramebuffer,\n clearColor: [0, 0, 0, 1],\n clearDepth: false\n });\n this.textureModel.draw(seedRenderPass);\n seedRenderPass.end();\n\n let previousFramebuffer: Framebuffer | null = sourceFramebuffer;\n let previousTexture: Texture = getFramebufferTexture(sourceFramebuffer);\n let frameSucceeded = false;\n try {\n for (const passRenderer of this.passRenderers) {\n passRenderer.initializeHistoryTargets(originalTexture, this.textureModel, commandEncoder);\n for (const execution of passRenderer.subPassExecutions) {\n const outputName = execution.output || 'previous';\n const outputFramebuffer: Framebuffer =\n outputName === 'previous'\n ? getNextPreviousFramebuffer(this.swapFramebuffers, previousFramebuffer)\n : passRenderer.getOutputFramebuffer(outputName);\n const outputTexture = getFramebufferTexture(outputFramebuffer);\n // Pipeline routing resolves logical input names like `original`, `previous`, or a named\n // render target into concrete textures for this draw.\n const resolvedBindings = passRenderer.resolveBindings({\n execution,\n originalTexture,\n previousTexture,\n outputTexture,\n externalBindings: options.bindings || {}\n });\n // Runtime uniforms are layered last so callers can update a renderer-owned pass without\n // reconstructing it every frame.\n const resolvedUniforms = resolveExecutionUniforms(\n this.shaderInputs,\n execution,\n options.uniforms || {}\n );\n\n execution.subPassRenderer.prepare({\n commandEncoder,\n bindings: resolvedBindings,\n textureScale: calculateTextureScale(\n (resolvedBindings['sourceTexture'] as Texture) || previousTexture,\n outputTexture\n ),\n uniforms: resolvedUniforms\n });\n const renderPass = commandEncoder.beginRenderPass({\n id: 'shader-pass-renderer-run-pass',\n framebuffer: outputFramebuffer,\n clearColor: [0, 0, 0, 1],\n clearDepth: 1\n });\n execution.subPassRenderer.draw(renderPass);\n renderPass.end();\n\n if (outputName === 'previous') {\n previousTexture = outputTexture;\n previousFramebuffer = outputFramebuffer;\n } else {\n passRenderer.markTargetWritten(outputName);\n }\n }\n }\n frameSucceeded = true;\n } finally {\n for (const passRenderer of this.passRenderers) {\n passRenderer.finishFrame(frameSucceeded);\n }\n }\n\n return previousTexture;\n }\n}\n\n/** Renders one `ShaderPass` or `ShaderPassPipeline` entry in the chain. */\nclass PassRenderer {\n device: Device;\n shaderInputs: ShaderInputs;\n passDefinition: ShaderPassLike;\n renderTargets: Record<string, ManagedRenderTarget>;\n subPassExecutions: EffectiveSubPass[];\n\n constructor(\n device: Device,\n passDefinition: ShaderPassLike,\n shaderInputs: ShaderInputs,\n flipY: boolean\n ) {\n this.device = device;\n this.shaderInputs = shaderInputs;\n this.passDefinition = passDefinition;\n\n if (isShaderPassPipeline(passDefinition)) {\n validateRenderTargetNames(passDefinition.name, passDefinition.renderTargets || {});\n this.renderTargets = createManagedRenderTargets(device, passDefinition.renderTargets || {});\n this.subPassExecutions = passDefinition.steps.flatMap(step =>\n this.createStepExecutions(passDefinition, step, flipY)\n );\n return;\n }\n\n validateShaderPassDoesNotOwnRenderTargets(passDefinition, passDefinition.name);\n this.renderTargets = {};\n this.subPassExecutions = this.createPassExecutions(passDefinition, {\n ownerName: passDefinition.name,\n flipY\n });\n }\n\n destroy() {\n for (const execution of this.subPassExecutions) {\n execution.subPassRenderer.destroy();\n }\n destroyManagedRenderTargets(this.renderTargets);\n }\n\n resize(size: [width: number, height: number]) {\n resizeManagedRenderTargets(this.device, this.renderTargets, size);\n }\n\n resetHistory(): void {\n for (const renderTarget of Object.values(this.renderTargets)) {\n renderTarget.historyInitialized = false;\n renderTarget.writtenThisFrame = false;\n }\n }\n\n initializeHistoryTargets(\n originalTexture: Texture,\n textureModel: BackgroundTextureModel,\n commandEncoder: CommandEncoder\n ): void {\n for (const renderTarget of Object.values(this.renderTargets)) {\n if (renderTarget.spec.lifetime !== 'history' || renderTarget.historyInitialized) {\n continue;\n }\n const historyFramebuffer = getHistoryFramebuffer(renderTarget);\n const initialize = renderTarget.spec.initialize || {\n clearColor: [0, 0, 0, 0] as [number, number, number, number]\n };\n if (initialize === 'original') {\n textureModel.setProps({backgroundTexture: originalTexture});\n textureModel.predraw(commandEncoder);\n const renderPass = commandEncoder.beginRenderPass({\n id: `${renderTarget.name}-initialize-history`,\n framebuffer: historyFramebuffer,\n clearColor: [0, 0, 0, 0],\n clearDepth: false\n });\n textureModel.draw(renderPass);\n renderPass.end();\n } else {\n const renderPass = commandEncoder.beginRenderPass({\n id: `${renderTarget.name}-clear-history`,\n framebuffer: historyFramebuffer,\n clearColor: initialize.clearColor,\n clearDepth: false\n });\n renderPass.end();\n }\n renderTarget.historyInitialized = true;\n }\n }\n\n getOutputFramebuffer(name: string): Framebuffer {\n return this.getRenderTarget(name).framebuffer;\n }\n\n markTargetWritten(name: string): void {\n this.getRenderTarget(name).writtenThisFrame = true;\n }\n\n finishFrame(succeeded: boolean): void {\n for (const renderTarget of Object.values(this.renderTargets)) {\n if (succeeded && renderTarget.spec.lifetime === 'history' && renderTarget.writtenThisFrame) {\n const historyTexture = getHistoryTexture(renderTarget);\n const historyFramebuffer = getHistoryFramebuffer(renderTarget);\n renderTarget.historyTexture = renderTarget.texture;\n renderTarget.historyFramebuffer = renderTarget.framebuffer;\n renderTarget.texture = historyTexture;\n renderTarget.framebuffer = historyFramebuffer;\n renderTarget.historyInitialized = true;\n }\n renderTarget.writtenThisFrame = false;\n }\n }\n\n getRenderTarget(name: string): ManagedRenderTarget {\n const renderTarget = this.renderTargets[name];\n if (!renderTarget) {\n throw new Error(`${this.getOwnerName()}: unknown render target \"${name}\"`);\n }\n return renderTarget;\n }\n\n resolveBindings(options: {\n execution: EffectiveSubPass;\n originalTexture: Texture;\n previousTexture: Texture;\n outputTexture: Texture;\n externalBindings: Record<string, ShaderPassBinding>;\n }): Record<string, ShaderPassBinding> {\n const {execution, originalTexture, previousTexture, outputTexture, externalBindings} = options;\n const inputMap = execution.inputs || {sourceTexture: 'previous'};\n const shaderInputBindings = this.shaderInputs.getModuleBindingValues(execution.shaderPass.name);\n const externalBindingsForPass = Object.fromEntries(\n Object.entries(externalBindings).filter(([name]) =>\n execution.shaderPass.bindingLayout?.some(binding => binding.name === name)\n )\n );\n // Shader-pass bindings stored in `shaderInputs` act as renderer-owned defaults. Per-draw\n // external bindings can override those defaults for frame-specific resources, while routed\n // logical inputs such as `sourceTexture` remain authoritative below.\n const resolvedBindings: Record<string, ShaderPassBinding> = {\n ...shaderInputBindings,\n ...externalBindingsForPass\n };\n const outputName = execution.output || 'previous';\n\n for (const [bindingName, inputSource] of Object.entries(inputMap)) {\n if (!inputSource) {\n continue;\n }\n const texture = this.resolveInputTexture(inputSource, originalTexture, previousTexture);\n const target = inputSource in this.renderTargets ? this.renderTargets[inputSource] : null;\n if (\n outputName !== 'previous' &&\n inputSource === outputName &&\n target?.spec.lifetime !== 'history'\n ) {\n throw new Error(\n `${execution.ownerName}: subpass cannot read and write render target \"${outputName}\" in the same draw`\n );\n }\n if (bindingName === 'sourceTexture' && texture === outputTexture) {\n throw new Error(\n `${execution.ownerName}: subpass cannot sample from the render target it is writing to`\n );\n }\n resolvedBindings[bindingName] = texture;\n }\n\n if (!('sourceTexture' in resolvedBindings)) {\n resolvedBindings['sourceTexture'] = previousTexture;\n }\n\n return resolvedBindings;\n }\n\n private createStepExecutions(\n pipeline: ShaderPassPipeline,\n step: ShaderPassPipeline['steps'][number],\n flipY: boolean\n ): EffectiveSubPass[] {\n validateShaderPassDoesNotOwnRenderTargets(\n step.shaderPass,\n `${pipeline.name}/${step.shaderPass.name}`\n );\n\n return this.createPassExecutions(step.shaderPass, {\n ownerName: `${pipeline.name}/${step.shaderPass.name}`,\n firstInputs: step.inputs,\n lastOutput: step.output,\n uniformOverrides: step.uniforms,\n flipY\n });\n }\n\n private createPassExecutions(\n shaderPass: ShaderPass,\n options: {\n ownerName: string;\n firstInputs?: Partial<Record<string, ShaderPassInputSource<string>>>;\n lastOutput?: 'previous' | string;\n uniformOverrides?: Record<string, unknown>;\n flipY: boolean;\n }\n ): EffectiveSubPass[] {\n const subPasses = shaderPass.passes || [];\n return subPasses.map((subPass, index) => {\n const isFirstSubPass = index === 0;\n const isLastSubPass = index === subPasses.length - 1;\n const inputs =\n isFirstSubPass && options.firstInputs !== undefined ? options.firstInputs : subPass.inputs;\n const output =\n isLastSubPass && options.lastOutput !== undefined ? options.lastOutput : subPass.output;\n validateSubPassRouting(options.ownerName, inputs, output, this.renderTargets);\n\n return {\n ownerName: options.ownerName,\n shaderPass,\n subPassRenderer: new SubPassRenderer(this.device, shaderPass, subPass, options.flipY),\n inputs,\n output,\n uniforms: mergeUniforms(options.uniformOverrides, subPass.uniforms)\n };\n });\n }\n\n private resolveInputTexture(\n inputSource: string,\n originalTexture: Texture,\n previousTexture: Texture\n ): Texture {\n switch (inputSource) {\n case 'original':\n return originalTexture;\n case 'previous':\n return previousTexture;\n default: {\n const renderTarget = this.getRenderTarget(inputSource);\n if (renderTarget.spec.lifetime === 'history' && !renderTarget.writtenThisFrame) {\n return getHistoryTexture(renderTarget);\n }\n return renderTarget.texture;\n }\n }\n }\n\n private getOwnerName(): string {\n return this.passDefinition.name;\n }\n}\n\n/** Renders a single subpass of a `ShaderPass`. */\nclass SubPassRenderer {\n model: ClipSpace;\n shaderPass: ShaderPass;\n subPass: ShaderSubPass;\n flipY: boolean;\n\n constructor(device: Device, shaderPass: ShaderPass, subPass: ShaderSubPass, flipY: boolean) {\n this.shaderPass = shaderPass;\n this.subPass = subPass;\n this.flipY = flipY;\n const action =\n subPass.action || (subPass.filter && 'filter') || (subPass.sampler && 'sample') || 'filter';\n const fs = getFragmentShaderForRenderPass({\n shaderPass,\n action,\n shadingLanguage: device.info.shadingLanguage\n });\n\n this.model = new ClipSpace(device, {\n id: `${shaderPass.name}-subpass`,\n source: fs,\n fs,\n modules: [textureTransform, shaderPass],\n parameters: {\n depthWriteEnabled: false\n }\n });\n }\n\n destroy() {\n this.model.destroy();\n }\n\n prepare(options: {\n commandEncoder: CommandEncoder;\n bindings: Record<string, ShaderPassBinding>;\n textureScale: [number, number];\n uniforms?: Record<string, unknown>;\n }): void {\n const {commandEncoder, bindings, textureScale, uniforms} = options;\n\n this.model.shaderInputs.setProps({\n textureTransform: {scale: textureScale, flipY: this.flipY ? 1 : 0}\n });\n this.model.shaderInputs.setProps({\n [this.shaderPass.name]: this.shaderPass.uniforms || {}\n });\n this.model.shaderInputs.setProps({\n [this.shaderPass.name]: uniforms || {}\n });\n this.model.setBindings(bindings || {});\n this.model.predraw(commandEncoder);\n }\n\n draw(renderPass: RenderPass): void {\n this.model.draw(renderPass);\n }\n}\n\nfunction getExecutableShaderPasses(shaderPasses: ShaderPassLike[]): ShaderPass[] {\n return shaderPasses.flatMap(shaderPass =>\n isShaderPassPipeline(shaderPass) ? shaderPass.steps.map(step => step.shaderPass) : [shaderPass]\n );\n}\n\nfunction isShaderPassPipeline(shaderPass: ShaderPassLike): shaderPass is ShaderPassPipeline {\n return 'steps' in shaderPass;\n}\n\nfunction validateShaderPassDoesNotOwnRenderTargets(\n shaderPass: ShaderPass,\n ownerName: string\n): void {\n const renderTargets = (shaderPass as ShaderPass & {renderTargets?: Record<string, unknown>})\n .renderTargets;\n if (renderTargets && Object.keys(renderTargets).length > 0) {\n throw new Error(\n `${ownerName}: ShaderPass.renderTargets is not supported; use ShaderPassPipeline.renderTargets instead`\n );\n }\n}\n\nfunction validateRenderTargetNames(\n ownerName: string,\n renderTargets: Record<string, ShaderPassRenderTarget>\n): void {\n for (const name of Object.keys(renderTargets)) {\n if (RESERVED_RENDER_TARGET_NAMES.has(name)) {\n throw new Error(`${ownerName}: render target name \"${name}\" is reserved`);\n }\n }\n}\n\nfunction validateSubPassRouting(\n ownerName: string,\n inputs: Partial<Record<string, ShaderPassInputSource<string>>> | undefined,\n output: 'previous' | string | undefined,\n renderTargets: Record<string, ManagedRenderTarget>\n): void {\n const inputMap = inputs || {sourceTexture: 'previous'};\n for (const inputSource of Object.values(inputMap)) {\n if (\n inputSource &&\n inputSource !== 'original' &&\n inputSource !== 'previous' &&\n !(inputSource in renderTargets)\n ) {\n throw new Error(`${ownerName}: unknown input source \"${inputSource}\"`);\n }\n }\n\n if (output && output !== 'previous' && !(output in renderTargets)) {\n throw new Error(`${ownerName}: unknown output target \"${output}\"`);\n }\n}\n\nfunction mergeUniforms(\n baseUniforms?: Record<string, unknown>,\n subPassUniforms?: Record<string, unknown>\n): Record<string, unknown> | undefined {\n if (!baseUniforms && !subPassUniforms) {\n return undefined;\n }\n\n return {\n ...(baseUniforms || {}),\n ...(subPassUniforms || {})\n };\n}\n\n/**\n * Resolves the effective uniform block for one execution.\n *\n * Merge order is:\n * 1. persisted renderer-level shader inputs\n * 2. uniforms baked into the pipeline or subpass definition\n * 3. per-draw runtime overrides\n */\nfunction resolveExecutionUniforms(\n shaderInputs: ShaderInputs,\n execution: EffectiveSubPass,\n runtimeUniforms: Record<string, Record<string, unknown>>\n): Record<string, unknown> | undefined {\n return mergeUniforms(\n mergeUniforms(\n shaderInputs.getUniformValues()[execution.shaderPass.name] as Record<string, unknown>,\n execution.uniforms\n ),\n runtimeUniforms[execution.shaderPass.name]\n );\n}\n\nfunction createManagedRenderTargets(\n device: Device,\n renderTargets: Record<string, ShaderPassRenderTarget>\n): Record<string, ManagedRenderTarget> {\n const size = device.getCanvasContext().getDrawingBufferSize();\n return Object.entries(renderTargets).reduce(\n (managedRenderTargets, [name, spec]) => ({\n ...managedRenderTargets,\n [name]: createManagedRenderTarget(device, name, spec, size)\n }),\n {} as Record<string, ManagedRenderTarget>\n );\n}\n\nfunction destroyManagedRenderTargets(renderTargets: Record<string, ManagedRenderTarget>): void {\n for (const renderTarget of Object.values(renderTargets)) {\n renderTarget.framebuffer.destroy();\n renderTarget.texture.destroy();\n renderTarget.historyFramebuffer?.destroy();\n renderTarget.historyTexture?.destroy();\n }\n}\n\nfunction resizeManagedRenderTargets(\n device: Device,\n renderTargets: Record<string, ManagedRenderTarget>,\n size: [width: number, height: number]\n): void {\n for (const renderTarget of Object.values(renderTargets)) {\n const targetSize = getRenderTargetSize(size, renderTarget.spec.scale);\n if (\n renderTarget.texture.width === targetSize[0] &&\n renderTarget.texture.height === targetSize[1]\n ) {\n continue;\n }\n\n renderTarget.framebuffer.destroy();\n renderTarget.texture.destroy();\n renderTarget.historyFramebuffer?.destroy();\n renderTarget.historyTexture?.destroy();\n const replacement = createManagedRenderTarget(\n device,\n renderTarget.name,\n renderTarget.spec,\n size\n );\n renderTarget.texture = replacement.texture;\n renderTarget.framebuffer = replacement.framebuffer;\n renderTarget.historyTexture = replacement.historyTexture;\n renderTarget.historyFramebuffer = replacement.historyFramebuffer;\n renderTarget.historyInitialized = false;\n renderTarget.writtenThisFrame = false;\n }\n}\n\nfunction createManagedRenderTarget(\n device: Device,\n name: string,\n spec: ShaderPassRenderTarget,\n size: [number, number]\n): ManagedRenderTarget {\n const targetSize = getRenderTargetSize(size, spec.scale);\n const {texture, framebuffer} = createTargetResources(device, name, spec, targetSize);\n let historyTexture: Texture | undefined;\n let historyFramebuffer: Framebuffer | undefined;\n if (spec.lifetime === 'history') {\n const historyResources = createTargetResources(device, `${name}-history`, spec, targetSize);\n historyTexture = historyResources.texture;\n historyFramebuffer = historyResources.framebuffer;\n }\n\n return {\n name,\n spec,\n texture,\n framebuffer,\n historyTexture,\n historyFramebuffer,\n historyInitialized: false,\n writtenThisFrame: false\n };\n}\n\nfunction createTargetResources(\n device: Device,\n name: string,\n spec: ShaderPassRenderTarget,\n targetSize: [number, number]\n): {texture: Texture; framebuffer: Framebuffer} {\n const texture = device.createTexture({\n id: `${name}-texture`,\n width: targetSize[0],\n height: targetSize[1],\n format: spec.format || device.preferredColorFormat,\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_SRC | Texture.COPY_DST,\n ...(spec.sampler ? {sampler: spec.sampler} : {})\n });\n const framebuffer = device.createFramebuffer({\n id: `${name}-framebuffer`,\n width: targetSize[0],\n height: targetSize[1],\n colorAttachments: [texture]\n });\n\n return {texture, framebuffer};\n}\n\nfunction getHistoryTexture(renderTarget: ManagedRenderTarget): Texture {\n if (!renderTarget.historyTexture) {\n throw new Error(`${renderTarget.name}: transient render target has no history texture`);\n }\n return renderTarget.historyTexture;\n}\n\nfunction getHistoryFramebuffer(renderTarget: ManagedRenderTarget): Framebuffer {\n if (!renderTarget.historyFramebuffer) {\n throw new Error(`${renderTarget.name}: transient render target has no history framebuffer`);\n }\n return renderTarget.historyFramebuffer;\n}\n\nfunction getRenderTargetSize(\n size: [width: number, height: number],\n scale: [number, number] = [1, 1]\n): [width: number, height: number] {\n return [Math.max(1, Math.round(size[0] * scale[0])), Math.max(1, Math.round(size[1] * scale[1]))];\n}\n\nfunction getFramebufferTexture(framebuffer: Framebuffer): Texture {\n const texture = framebuffer.colorAttachments[0]?.texture;\n if (!texture) {\n throw new Error('ShaderPassRenderer: framebuffer is missing a color attachment texture');\n }\n return texture;\n}\n\nfunction getNextPreviousFramebuffer(\n swapFramebuffers: SwapFramebuffers,\n previousFramebuffer: Framebuffer | null\n): Framebuffer {\n if (previousFramebuffer === swapFramebuffers.current) {\n return swapFramebuffers.next;\n }\n return swapFramebuffers.current;\n}\n\nfunction getSeedFramebuffer(\n swapFramebuffers: SwapFramebuffers,\n originalTexture: Texture\n): Framebuffer {\n if (getFramebufferTexture(swapFramebuffers.current) === originalTexture) {\n return swapFramebuffers.next;\n }\n return swapFramebuffers.current;\n}\n\nfunction calculateTextureScale(\n sourceTexture: Texture,\n outputTexture: Texture\n): [scaleX: number, scaleY: number] {\n const sourceAspect = sourceTexture.width / sourceTexture.height;\n const outputAspect = outputTexture.width / outputTexture.height;\n\n if (outputAspect > sourceAspect) {\n return [1, outputAspect / sourceAspect];\n }\n\n return [sourceAspect / outputAspect, 1];\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {BufferProps, FramebufferProps} from '@luma.gl/core';\nimport {Device, Resource, Buffer, Framebuffer, Texture} from '@luma.gl/core';\n\n/**\n * Helper class for working with repeated transformations / computations\n * Primarily intended for GPU buffers `Swap<Buffer>` or textures `Swap<Texture>`)\n * @note the two resources are expected to be structurally identical (same size, length, format, etc)\n * @note the two resources can be destroyed by calling `destroy()`\n */\nexport class Swap<T extends Resource<any>> {\n id: string;\n\n /** The current resource - usually the source for renders or computations */\n current: T;\n /** The next resource - usually the target/destination for transforms / computations */\n next: T;\n\n constructor(props: {current: T; next: T; id?: string}) {\n this.id = props.id || 'swap';\n this.current = props.current;\n this.next = props.next;\n }\n\n /** Destroys the two managed resources */\n destroy() {\n this.current?.destroy();\n this.next?.destroy();\n }\n\n /** Make the next resource into the current resource, and reuse the current resource as the next resource */\n swap() {\n const current = this.current;\n this.current = this.next;\n this.next = current;\n }\n}\n\n/** Helper for managing double-buffered framebuffers */\nexport class SwapFramebuffers extends Swap<Framebuffer> {\n constructor(device: Device, props: FramebufferProps) {\n props = {...props};\n\n const {width = 1, height = 1} = props;\n\n let colorAttachments = props.colorAttachments?.map(colorAttachment =>\n typeof colorAttachment !== 'string'\n ? colorAttachment\n : device.createTexture({\n id: `${props.id}-texture-0`,\n format: colorAttachment,\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_SRC | Texture.COPY_DST,\n width,\n height\n })\n );\n\n const current = device.createFramebuffer({...props, colorAttachments});\n\n colorAttachments = props.colorAttachments?.map(colorAttachment =>\n typeof colorAttachment !== 'string'\n ? colorAttachment\n : device.createTexture({\n id: `${props.id}-texture-1`,\n format: colorAttachment,\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_SRC | Texture.COPY_DST,\n width,\n height\n })\n );\n\n const next = device.createFramebuffer({...props, colorAttachments});\n\n super({current, next});\n\n for (const [index, colorAttachment] of (props.colorAttachments || []).entries()) {\n if (typeof colorAttachment === 'string') {\n current.attachResource(current.colorAttachments[index].texture);\n next.attachResource(next.colorAttachments[index].texture);\n }\n }\n }\n\n /**\n * Resizes the Framebuffers.\n * @returns true if the size changed, otherwise exiting framebuffers were preserved\n * @note any contents are not preserved!\n */\n resize(size: {width: number; height: number}): boolean {\n if (size.width === this.current.width && size.height === this.current.height) {\n return false;\n }\n const {current, next} = this;\n\n this.current = current.clone(size);\n attachFramebufferAttachments(this.current);\n current.destroy();\n\n this.next = next.clone(size);\n attachFramebufferAttachments(this.next);\n next.destroy();\n\n return true;\n }\n}\n\n/** Framebuffer.clone() creates fresh attachments that the replacement framebuffer must own. */\nfunction attachFramebufferAttachments(framebuffer: Framebuffer): void {\n for (const colorAttachment of framebuffer.colorAttachments) {\n framebuffer.attachResource(colorAttachment.texture);\n }\n if (framebuffer.depthStencilAttachment) {\n framebuffer.attachResource(framebuffer.depthStencilAttachment.texture);\n }\n}\n\n/** Helper for managing double-buffered GPU buffers */\nexport class SwapBuffers extends Swap<Buffer> {\n constructor(device: Device, props: BufferProps) {\n super({current: device.createBuffer(props), next: device.createBuffer(props)});\n }\n\n /**\n * Resizes the Buffers.\n * @returns true if the size changed, otherwise exiting buffers were preserved.\n * @note any contents are not preserved!\n */\n resize(props: {byteLength: number}) {\n if (props.byteLength === this.current.byteLength) {\n return false;\n }\n\n const {current, next} = this;\n\n this.current = current.clone(props);\n current.destroy();\n\n this.next = next.clone(props);\n next.destroy();\n\n return true;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderPass} from '@luma.gl/shadertools';\n\n/**\n * Gets fragment shader source for a shader pass sub pass\n * @param options\n * @returns\n */\nexport function getFragmentShaderForRenderPass(options: {\n shaderPass: ShaderPass;\n action: 'filter' | 'sample';\n shadingLanguage: 'wgsl' | 'glsl';\n}): string {\n const {shaderPass, action, shadingLanguage} = options;\n switch (action) {\n case 'filter':\n const filterFunc = `${shaderPass.name}_filterColor_ext`;\n return shadingLanguage === 'wgsl'\n ? getFilterShaderWGSL(filterFunc)\n : getFilterShaderGLSL(filterFunc);\n\n case 'sample':\n const samplerFunc = `${shaderPass.name}_sampleColor`;\n return shadingLanguage === 'wgsl'\n ? getSamplerShaderWGSL(samplerFunc)\n : getSamplerShaderGLSL(samplerFunc);\n\n default:\n throw new Error(`${shaderPass.name} no fragment shader generated for shader pass`);\n }\n}\n\n/** Get a filtering WGSL fragment shader */\nfunction getFilterShaderWGSL(func: string) {\n return /* wgsl */ `\\\n@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;\n@group(0) @binding(auto) var sourceTextureSampler: sampler;\n\n@fragment\nfn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {\n let texCoord = shaderPassRenderer_getTextureUV(inputs.coordinate);\n let texSize = vec2f(textureDimensions(sourceTexture));\n\n var fragColor = textureSample(sourceTexture, sourceTextureSampler, texCoord);\n fragColor = ${func}(fragColor, texSize, texCoord);\n return fragColor;\n}\n`;\n}\n\n/** Get a sampling WGSL fragment shader */\nfunction getSamplerShaderWGSL(func: string) {\n return /* wgsl */ `\\\n@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;\n@group(0) @binding(auto) var sourceTextureSampler: sampler;\n\n@fragment\nfn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {\n let texCoord = shaderPassRenderer_getTextureUV(inputs.coordinate);\n let texSize = vec2f(textureDimensions(sourceTexture));\n return ${func}(sourceTexture, sourceTextureSampler, texSize, texCoord);\n}\n`;\n}\n\n/** Get a filtering GLSL fragment shader */\nfunction getFilterShaderGLSL(func: string) {\n return /* glsl */ `\\\n#version 300 es\n\nuniform sampler2D sourceTexture;\n\nin vec2 position;\nin vec2 coordinate;\nin vec2 uv;\n\nout vec4 fragColor;\n\nvoid main() {\n vec2 texCoord = shaderPassRenderer_getTextureUV(coordinate);\n ivec2 iTexSize = textureSize(sourceTexture, 0);\n vec2 texSize = vec2(float(iTexSize.x), float(iTexSize.y));\n\n fragColor = texture(sourceTexture, texCoord);\n fragColor = ${func}(fragColor, texSize, texCoord);\n}\n`;\n}\n\n/** Get a sampling GLSL fragment shader */\nfunction getSamplerShaderGLSL(func: string) {\n return /* glsl */ `\\\n#version 300 es\n\nuniform sampler2D sourceTexture;\n\nin vec2 position;\nin vec2 coordinate;\nin vec2 uv;\n\nout vec4 fragColor;\n\nvoid main() {\n vec2 texCoord = shaderPassRenderer_getTextureUV(coordinate);\n ivec2 iTexSize = textureSize(sourceTexture, 0);\n vec2 texSize = vec2(float(iTexSize.x), float(iTexSize.y));\n\n fragColor = ${func}(sourceTexture, texSize, texCoord);\n}\n`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nexport const textureTransform = {\n name: 'textureTransform',\n source: /* wgsl */ `\nstruct textureTransformUniforms {\n scale: vec2<f32>,\n flipY: i32,\n};\n@group(0) @binding(auto) var<uniform> textureTransform: textureTransformUniforms;\n\nfn shaderPassRenderer_getTextureUV(uv: vec2f) -> vec2f {\n var position = (uv - vec2f(0.5, 0.5)) / textureTransform.scale + vec2f(0.5, 0.5);\n if (textureTransform.flipY != 0) {\n position.y = 1.0 - position.y;\n }\n return position;\n}\n\nfn shaderPassRenderer_getRenderTargetUV(textureUV: vec2f) -> vec2f {\n let unscaledCoord = (textureUV - vec2f(0.5, 0.5)) * textureTransform.scale + vec2f(0.5, 0.5);\n return select(vec2f(unscaledCoord.x, 1.0 - unscaledCoord.y), unscaledCoord, textureTransform.flipY != 0);\n}\n`,\n fs: /* glsl */ `\nlayout(std140) uniform textureTransformUniforms {\n vec2 scale;\n int flipY;\n} textureTransform;\n\nvec2 shaderPassRenderer_getTextureUV(vec2 coord) {\n vec2 position = (coord - 0.5) / textureTransform.scale + 0.5;\n if (textureTransform.flipY != 0) {\n position.y = 1.0 - position.y;\n }\n return position;\n}\n\nvec2 shaderPassRenderer_getRenderTargetUV(vec2 textureUV) {\n vec2 unscaledCoord = (textureUV - 0.5) * textureTransform.scale + 0.5;\n return textureTransform.flipY != 0 ? unscaledCoord : vec2(unscaledCoord.x, 1.0 - unscaledCoord.y);\n}\n`,\n uniformTypes: {\n scale: 'vec2<f32>',\n flipY: 'i32'\n }\n} as const satisfies ShaderModule<{}, {scale: [number, number]; flipY: number}>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n type DeviceFeature,\n type ComputePipelineProps,\n type Shader,\n type Binding,\n type CommandEncoder,\n Device,\n Buffer,\n ComputePipeline,\n ComputePass,\n PipelineFactory,\n ShaderFactory,\n UniformStore,\n log,\n dataTypeDecoder\n} from '@luma.gl/core';\nimport {\n type ShaderModule,\n type ShaderPlugin,\n type PlatformInfo,\n mergeShaderPluginModules,\n resolveShaderPlugins,\n ShaderAssembler\n} from '@luma.gl/shadertools';\nimport {type TypedArray, isNumericArray} from '@math.gl/types';\nimport {ShaderInputs} from '../shader-inputs';\nimport {\n mergeShaderModules,\n mergeShaderModuleBindingsIntoLayout,\n shaderModuleHasUniforms\n} from '../utils/shader-module-utils';\nimport {uid} from '../utils/uid';\n// import {getDebugTableForShaderLayout} from '../debug/debug-shader-layout';\n\nconst LOG_DRAW_PRIORITY = 2;\nconst LOG_DRAW_TIMEOUT = 10000;\n\nexport type ComputationProps = Omit<ComputePipelineProps, 'shader'> & {\n source?: string;\n\n /** Shadertools shader modules added to shader code. */\n modules?: ShaderModule[];\n /** Shadertools boolean or numeric preprocessor defines that configure shader code. */\n defines?: Record<string, boolean | number>;\n /** Reusable shader assembly plugins resolved for WGSL compute assembly. */\n plugins?: ShaderPlugin[];\n\n /** Shader inputs, used to generate uniform buffers and bindings. */\n shaderInputs?: ShaderInputs;\n\n /** Bindings */\n bindings?: Record<string, Binding>;\n\n /** Show shader source in browser? */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n\n /** Factory used to create a {@link ComputePipeline}. Defaults to {@link Device} default factory. */\n pipelineFactory?: PipelineFactory;\n /** Factory used to create a {@link Shader}. Defaults to {@link Device} default factory. */\n shaderFactory?: ShaderFactory;\n /** Shader assembler. Defaults to the ShaderAssembler.getShaderAssembler() */\n shaderAssembler?: ShaderAssembler;\n};\n\n/**\n * v9 Model API\n * A model\n * - automatically reuses pipelines (programs) when possible\n * - automatically rebuilds pipelines if necessary to accommodate changed settings\n * shadertools integration\n * - accepts modules and performs shader transpilation\n */\nexport class Computation {\n static defaultProps: Required<ComputationProps> = {\n ...ComputePipeline.defaultProps,\n id: 'unnamed',\n handle: undefined,\n userData: {},\n\n source: '',\n modules: [],\n defines: {},\n plugins: [],\n\n bindings: undefined!,\n shaderInputs: undefined!,\n\n pipelineFactory: undefined!,\n shaderFactory: undefined!,\n shaderAssembler: ShaderAssembler.getDefaultShaderAssembler(),\n\n debugShaders: undefined!\n };\n\n readonly device: Device;\n readonly id: string;\n\n readonly pipelineFactory: PipelineFactory;\n readonly shaderFactory: ShaderFactory;\n\n userData: {[key: string]: any} = {};\n\n /** Bindings (textures, samplers, uniform buffers) */\n bindings: Record<string, Binding> = {};\n\n /** The underlying GPU pipeline. */\n pipeline: ComputePipeline;\n /** Assembled compute shader source */\n source: string;\n /** the underlying compiled compute shader */\n // @ts-ignore Set in function called from constructor\n shader: Shader;\n\n /** ShaderInputs instance */\n shaderInputs: ShaderInputs;\n\n // @ts-ignore Set in function called from constructor\n _uniformStore: UniformStore;\n\n _pipelineNeedsUpdate: string | false = 'newly created';\n\n private _getModuleUniforms: (props?: Record<string, Record<string, any>>) => Record<string, any>;\n private props: Required<ComputationProps>;\n\n private _destroyed = false;\n\n constructor(device: Device, props: ComputationProps) {\n if (device.type !== 'webgpu') {\n throw new Error('Computation is only supported in WebGPU');\n }\n\n this.props = {...Computation.defaultProps, ...props};\n props = this.props;\n this.id = props.id || uid('model');\n this.device = device;\n\n Object.assign(this.userData, props.userData);\n\n const platformInfo = getPlatformInfo(device);\n const resolvedPlugins = resolveShaderPlugins(this.props.plugins, platformInfo.shaderLanguage);\n if (\n Object.keys(resolvedPlugins.vertexInputs).length > 0 ||\n Object.keys(resolvedPlugins.varyings).length > 0\n ) {\n throw new Error('Computation does not support ShaderPlugin vertex inputs or varyings');\n }\n\n // Setup shader module inputs\n const shaderInputModules = mergeShaderPluginModules(\n this.props.modules,\n resolvedPlugins.modules\n );\n const moduleMap = Object.fromEntries(shaderInputModules.map(module => [module.name, module]));\n // @ts-ignore TODO - fix up typing?\n this.shaderInputs = props.shaderInputs || new ShaderInputs(moduleMap);\n if (props.shaderInputs && resolvedPlugins.modules.length > 0) {\n this.shaderInputs.addModules(resolvedPlugins.modules);\n }\n this.setShaderInputs(this.shaderInputs);\n\n // Setup shader assembler\n const modules = mergeShaderModules(this.props.modules, this.shaderInputs?.getModules());\n const defines = {...resolvedPlugins.defines, ...this.props.defines};\n\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(this.props.shaderLayout, modules) || null;\n\n this.pipelineFactory =\n props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);\n this.shaderFactory = props.shaderFactory || ShaderFactory.getDefaultShaderFactory(this.device);\n\n const {source, getUniforms} = this.props.shaderAssembler.assembleWGSLShader({\n platformInfo,\n ...this.props,\n modules,\n defines,\n pluginInjections: resolvedPlugins.injections\n });\n\n this.source = source;\n // @ts-ignore\n this._getModuleUniforms = getUniforms;\n const inferredShaderLayout = (\n device as Device & {getShaderLayout?: (source: string) => any}\n ).getShaderLayout?.(this.source);\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(\n this.props.shaderLayout || inferredShaderLayout || null,\n modules\n ) || null;\n\n // Create the pipeline\n // @note order is important\n this.pipeline = this._updatePipeline();\n\n // Apply any dynamic settings that will not trigger pipeline change\n if (props.bindings) {\n this.setBindings(props.bindings);\n }\n }\n\n destroy(): void {\n if (this._destroyed) return;\n this.pipelineFactory.release(this.pipeline);\n this.shaderFactory.release(this.shader);\n this._uniformStore.destroy();\n this._destroyed = true;\n }\n\n // Draw call\n\n /**\n * Updates compute shader inputs before opening the compute pass that will\n * consume them.\n */\n predraw(commandEncoder: CommandEncoder) {\n // Update uniform buffers if needed\n this.updateShaderInputs(commandEncoder);\n }\n\n dispatch(computePass: ComputePass, x: number, y?: number, z?: number): void {\n try {\n this._logDrawCallStart();\n\n // Check if the pipeline is invalidated\n // TODO - this is likely the worst place to do this from performance perspective. Perhaps add a predraw()?\n this.pipeline = this._updatePipeline();\n\n // Set pipeline state, we may be sharing a pipeline so we need to set all state on every draw\n // Any caching needs to be done inside the pipeline functions\n this.pipeline.setBindings(this.bindings);\n computePass.setPipeline(this.pipeline);\n // @ts-expect-error\n computePass.setBindings({});\n\n computePass.dispatch(x, y, z);\n } finally {\n this._logDrawCallEnd();\n }\n }\n\n // Update fixed fields (can trigger pipeline rebuild)\n\n // Update dynamic fields\n\n /**\n * Updates the vertex count (used in draw calls)\n * @note Any attributes with stepMode=vertex need to be at least this big\n */\n setVertexCount(vertexCount: number): void {\n // this.vertexCount = vertexCount;\n }\n\n /**\n * Updates the instance count (used in draw calls)\n * @note Any attributes with stepMode=instance need to be at least this big\n */\n setInstanceCount(instanceCount: number): void {\n // this.instanceCount = instanceCount;\n }\n\n setShaderInputs(shaderInputs: ShaderInputs): void {\n this.shaderInputs = shaderInputs;\n this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules);\n // Create uniform buffer bindings for all modules\n for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) {\n if (shaderModuleHasUniforms(module)) {\n const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName);\n this.bindings[`${moduleName}Uniforms`] = uniformBuffer;\n }\n }\n }\n\n /**\n * Updates shader module settings (which results in uniforms being set)\n */\n setShaderModuleProps(props: Record<string, any>): void {\n const uniforms = this._getModuleUniforms(props);\n\n // Extract textures & framebuffers set by the modules\n // TODO better way to extract bindings\n const keys = Object.keys(uniforms).filter(k => {\n const uniform = uniforms[k];\n return (\n !isNumericArray(uniform) && typeof uniform !== 'number' && typeof uniform !== 'boolean'\n );\n });\n const bindings: Record<string, Binding> = {};\n for (const k of keys) {\n bindings[k] = uniforms[k];\n delete uniforms[k];\n }\n }\n\n /**\n * Flushes current shader-input values into the internal uniform store.\n *\n * @param commandEncoder - Optional encoder used to order uniform uploads with\n * subsequent compute commands.\n */\n updateShaderInputs(commandEncoder?: CommandEncoder): void {\n this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(), commandEncoder);\n }\n\n /**\n * Sets bindings (textures, samplers, uniform buffers)\n */\n setBindings(bindings: Record<string, Binding>): void {\n Object.assign(this.bindings, bindings);\n }\n\n _setPipelineNeedsUpdate(reason: string): void {\n this._pipelineNeedsUpdate = this._pipelineNeedsUpdate || reason;\n }\n\n _updatePipeline(): ComputePipeline {\n if (this._pipelineNeedsUpdate) {\n let prevShader: Shader | null = null;\n if (this.pipeline) {\n log.log(\n 1,\n `Model ${this.id}: Recreating pipeline because \"${this._pipelineNeedsUpdate}\".`\n )();\n prevShader = this.shader;\n }\n\n this._pipelineNeedsUpdate = false;\n\n this.shader = this.shaderFactory.createShader({\n id: `${this.id}-fragment`,\n stage: 'compute',\n source: this.source,\n debugShaders: this.props.debugShaders\n });\n\n this.pipeline = this.pipelineFactory.createComputePipeline({\n ...this.props,\n shader: this.shader\n });\n\n if (prevShader) {\n this.shaderFactory.release(prevShader);\n }\n }\n return this.pipeline;\n }\n\n /** Throttle draw call logging */\n _lastLogTime = 0;\n _logOpen = false;\n\n _logDrawCallStart(): void {\n // IF level is 4 or higher, log every frame.\n const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;\n if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {\n return;\n }\n\n this._lastLogTime = Date.now();\n this._logOpen = true;\n\n log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {collapsed: log.level <= 2})();\n }\n\n _logDrawCallEnd(): void {\n if (this._logOpen) {\n // const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.props.shaderLayout, this.id);\n\n // log.table(logLevel, attributeTable)();\n // log.table(logLevel, uniformTable)();\n // log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();\n\n const uniformTable = this.shaderInputs.getDebugTable();\n log.table(LOG_DRAW_PRIORITY, uniformTable)();\n\n log.groupEnd(LOG_DRAW_PRIORITY)();\n this._logOpen = false;\n }\n }\n\n protected _drawCount = 0;\n\n // TODO - fix typing of luma data types\n _getBufferOrConstantValues(attribute: Buffer | TypedArray, dataType: any): string {\n const TypedArrayConstructor = dataTypeDecoder.getTypedArrayConstructor(dataType);\n const typedArray =\n attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;\n return typedArray.toString();\n }\n}\n\n/** Create a shadertools platform info from the Device */\nexport function getPlatformInfo(device: Device): PlatformInfo {\n return {\n type: device.type,\n shaderLanguage: device.info.shadingLanguage,\n shaderLanguageVersion: device.info.shadingLanguageVersion as 100 | 300,\n gpu: device.info.gpu,\n limits: device.limits as unknown as Record<string, number | undefined>,\n // HACK - we pretend that the DeviceFeatures is a Set, it has a similar API\n features: device.features as unknown as Set<DeviceFeature>\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Buffer, Device, Framebuffer, Texture} from '@luma.gl/core';\nimport {ShaderInputs} from '../../shader-inputs';\nimport {pickingUniforms, INVALID_INDEX} from './picking-uniforms';\n\nconst INDEX_PICKING_ATTACHMENT_INDEX = 1;\nconst INDEX_PICKING_CLEAR_COLOR = new Int32Array([INVALID_INDEX, INVALID_INDEX, 0, 0]);\nconst COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst COLOR_PICKING_MAX_BATCH_INDEX = 254;\nconst TOOLTIP_OFFSET_PIXELS = 14;\nconst TOOLTIP_MARGIN_PIXELS = 8;\n\n/** Information about picked object */\nexport type PickInfo = {\n batchIndex: number | null;\n objectIndex: number | null;\n};\n\n/** Text shown by `PickingManager` beside the latest picked cursor position. */\nexport type PickingTooltip = string | null;\n\nexport type PickingMode = 'auto' | 'index' | 'color';\nexport type ResolvedPickingMode = Exclude<PickingMode, 'auto'>;\nexport type PickingShouldPickOptions = {\n /** Re-render picking even when the cursor has not moved. */\n force?: boolean;\n};\n/** @deprecated Use `PickingMode`. */\nexport type PickingBackend = PickingMode;\n/** @deprecated Use `ResolvedPickingMode`. */\nexport type ResolvedPickingBackend = ResolvedPickingMode;\n\nexport type PickingManagerProps = {\n /** Shader inputs from models to pick */\n shaderInputs?: ShaderInputs<{picking: typeof pickingUniforms.props}>;\n /** Callback */\n onObjectPicked?: (info: PickInfo) => void;\n /**\n * Returns tooltip text for the latest pick result.\n * Returning `null` hides the tooltip.\n */\n getTooltip?: (info: PickInfo) => PickingTooltip;\n /** Select a picking mode. Defaults to `color`. Use `auto` to prefer `index` when supported. */\n mode?: PickingMode;\n /** @deprecated Use `mode`. */\n backend?: PickingBackend;\n};\n\nexport function resolvePickingMode(\n deviceType: Device['type'],\n mode: PickingMode = 'color',\n indexPickingSupported: boolean = deviceType === 'webgpu'\n): ResolvedPickingMode {\n if (mode === 'auto') {\n return indexPickingSupported ? 'index' : 'color';\n }\n\n if (mode === 'index' && !indexPickingSupported) {\n throw new Error(\n `Picking mode \"${mode}\" requires WebGPU or a WebGL device that supports renderable rg32sint textures.`\n );\n }\n\n return mode;\n}\n\nexport function supportsIndexPicking(device: Device): boolean {\n return (\n device.type === 'webgpu' ||\n (device.type === 'webgl' && device.isTextureFormatRenderable('rg32sint'))\n );\n}\n\n/** @deprecated Use `resolvePickingMode`. */\nexport const resolvePickingBackend = resolvePickingMode;\n\nexport function decodeIndexPickInfo(pixelData: Int32Array): PickInfo {\n return {\n objectIndex: pixelData[0] === INVALID_INDEX ? null : pixelData[0],\n batchIndex: pixelData[1] === INVALID_INDEX ? null : pixelData[1]\n };\n}\n\nexport function decodeColorPickInfo(pixelData: Uint8Array): PickInfo {\n const encodedObjectIndex = pixelData[0] + pixelData[1] * 256 + pixelData[2] * 65536;\n if (encodedObjectIndex === 0) {\n return {objectIndex: null, batchIndex: null};\n }\n\n const batchIndex = pixelData[3] > 0 ? pixelData[3] - 1 : 0;\n return {\n objectIndex: encodedObjectIndex - 1,\n batchIndex\n };\n}\n\n/**\n * Helper class for using object picking with backend-specific readback.\n * @todo Support multiple models\n * @todo Switching picking module\n */\nexport class PickingManager {\n device: Device;\n props: Required<PickingManagerProps>;\n mode: ResolvedPickingMode;\n /** Info from latest pick operation */\n pickInfo: PickInfo = {batchIndex: null, objectIndex: null};\n /** Framebuffer used for picking */\n framebuffer: Framebuffer | null = null;\n /** Last cursor position that triggered a picking render/readback. */\n protected lastMousePosition: [number, number] | null = null;\n /** Tooltip element created lazily when `getTooltip` returns visible content. */\n protected tooltipElement: HTMLDivElement | null = null;\n\n static defaultProps: Required<PickingManagerProps> = {\n shaderInputs: undefined!,\n onObjectPicked: () => {},\n getTooltip: () => null,\n mode: 'color',\n backend: 'color'\n };\n\n constructor(device: Device, props: PickingManagerProps) {\n this.device = device;\n this.props = {...PickingManager.defaultProps, ...props};\n const requestedMode = props.mode ?? props.backend ?? PickingManager.defaultProps.mode;\n this.props.mode = requestedMode;\n this.props.backend = requestedMode;\n this.mode = resolvePickingMode(\n this.device.type,\n requestedMode,\n supportsIndexPicking(this.device)\n );\n }\n\n destroy() {\n this.framebuffer?.destroy();\n this.tooltipElement?.remove();\n this.tooltipElement = null;\n }\n\n // TODO - Ask for a cached framebuffer? a Framebuffer factory?\n getFramebuffer() {\n if (!this.framebuffer) {\n this.framebuffer =\n this.mode === 'index' ? this.createIndexFramebuffer() : this.createColorFramebuffer();\n }\n return this.framebuffer;\n }\n\n /** Clear highlighted / picked object */\n clearPickState() {\n this.lastMousePosition = null;\n this.setPickingProps({highlightedBatchIndex: null, highlightedObjectIndex: null});\n this.hideTooltip();\n }\n\n /** Return whether callers need to render a fresh picking pass for this cursor position. */\n shouldPick(\n mousePosition: [number, number] | null | undefined,\n options: PickingShouldPickOptions = {}\n ): mousePosition is [number, number] {\n if (!mousePosition) {\n if (this.lastMousePosition) {\n this.clearPickState();\n }\n return false;\n }\n\n const [mouseX, mouseY] = mousePosition;\n if (\n !options.force &&\n this.lastMousePosition &&\n this.lastMousePosition[0] === mouseX &&\n this.lastMousePosition[1] === mouseY\n ) {\n return false;\n }\n\n this.lastMousePosition = [mouseX, mouseY];\n return true;\n }\n\n /** Prepare for rendering picking colors */\n beginRenderPass() {\n const framebuffer = this.getFramebuffer();\n framebuffer.resize(this.device.getDefaultCanvasContext().getDevicePixelSize());\n\n this.setPickingProps({isActive: true});\n\n return this.mode === 'index'\n ? this.device.beginRenderPass({\n framebuffer,\n clearColors: [new Float32Array([0, 0, 0, 0]), INDEX_PICKING_CLEAR_COLOR],\n clearDepth: 1\n })\n : this.device.beginRenderPass({\n framebuffer,\n clearColor: [0, 0, 0, 0],\n clearDepth: 1\n });\n }\n\n async updatePickInfo(mousePosition: [number, number]): Promise<PickInfo | null> {\n const framebuffer = this.getFramebuffer();\n const pickPosition = this.getPickPosition(mousePosition);\n const pickInfo = await this.readPickInfo(framebuffer, pickPosition);\n if (!pickInfo) {\n return null;\n }\n\n if (this.hasPickInfoChanged(pickInfo)) {\n this.pickInfo = pickInfo;\n this.props.onObjectPicked(pickInfo);\n }\n\n this.updateTooltip(pickInfo, mousePosition);\n this.setPickingProps({\n isActive: false,\n highlightedBatchIndex: pickInfo.batchIndex,\n highlightedObjectIndex: pickInfo.objectIndex\n });\n\n return this.pickInfo;\n }\n\n /**\n * Get pick position in device pixel range\n * use the center pixel location in device pixel range\n */\n getPickPosition(mousePosition: [number, number]): [number, number] {\n const yInvert = this.device.type !== 'webgpu';\n const devicePixels = this.device\n .getDefaultCanvasContext()\n .cssToDevicePixels(mousePosition, yInvert);\n const pickX = devicePixels.x + Math.floor(devicePixels.width / 2);\n const pickY = devicePixels.y + Math.floor(devicePixels.height / 2);\n return [pickX, pickY];\n }\n\n protected createIndexFramebuffer(): Framebuffer {\n const colorTexture = this.device.createTexture({\n format: 'rgba8unorm',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT\n });\n const pickingTexture = this.device.createTexture({\n format: 'rg32sint',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC\n });\n\n return this.device.createFramebuffer({\n colorAttachments: [colorTexture, pickingTexture],\n depthStencilAttachment: 'depth24plus'\n });\n }\n\n protected createColorFramebuffer(): Framebuffer {\n const pickingTexture = this.device.createTexture({\n format: 'rgba8unorm',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC\n });\n\n return this.device.createFramebuffer({\n colorAttachments: [pickingTexture],\n depthStencilAttachment: 'depth24plus'\n });\n }\n\n protected setPickingProps(props: Partial<typeof pickingUniforms.props>): void {\n this.props.shaderInputs?.setProps({picking: props});\n }\n\n protected async readPickInfo(\n framebuffer: Framebuffer,\n pickPosition: [number, number]\n ): Promise<PickInfo | null> {\n return this.mode === 'index'\n ? this.readIndexPickInfo(framebuffer, pickPosition)\n : this.readColorPickInfo(framebuffer, pickPosition);\n }\n\n protected async readIndexPickInfo(\n framebuffer: Framebuffer,\n [pickX, pickY]: [number, number]\n ): Promise<PickInfo | null> {\n if (this.device.type === 'webgpu') {\n const pickTexture = framebuffer.colorAttachments[INDEX_PICKING_ATTACHMENT_INDEX]?.texture;\n if (!pickTexture) {\n return null;\n }\n\n const layout = pickTexture.computeMemoryLayout({width: 1, height: 1});\n const readBuffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n try {\n pickTexture.readBuffer(\n {\n x: pickX,\n y: pickY,\n width: 1,\n height: 1\n },\n readBuffer\n );\n const pickDataView = await readBuffer.readAsync(0, layout.byteLength);\n return decodeIndexPickInfo(new Int32Array(pickDataView.buffer, pickDataView.byteOffset, 2));\n } finally {\n readBuffer.destroy();\n }\n }\n\n const pixelData = this.device.readPixelsToArrayWebGL(framebuffer, {\n sourceX: pickX,\n sourceY: pickY,\n sourceWidth: 1,\n sourceHeight: 1,\n sourceAttachment: INDEX_PICKING_ATTACHMENT_INDEX\n });\n\n return pixelData\n ? decodeIndexPickInfo(new Int32Array(pixelData.buffer, pixelData.byteOffset, 2))\n : null;\n }\n\n protected async readColorPickInfo(\n framebuffer: Framebuffer,\n [pickX, pickY]: [number, number]\n ): Promise<PickInfo | null> {\n if (this.device.type === 'webgpu') {\n const pickTexture = framebuffer.colorAttachments[0]?.texture;\n if (!pickTexture) {\n return null;\n }\n\n const layout = pickTexture.computeMemoryLayout({width: 1, height: 1});\n const readBuffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n try {\n pickTexture.readBuffer(\n {\n x: pickX,\n y: pickY,\n width: 1,\n height: 1\n },\n readBuffer\n );\n const pickDataView = await readBuffer.readAsync(0, layout.byteLength);\n return decodeColorPickInfo(new Uint8Array(pickDataView.buffer, pickDataView.byteOffset, 4));\n } finally {\n readBuffer.destroy();\n }\n }\n\n const pixelData = this.device.readPixelsToArrayWebGL(framebuffer, {\n sourceX: pickX,\n sourceY: pickY,\n sourceWidth: 1,\n sourceHeight: 1,\n sourceAttachment: 0\n });\n\n return pixelData\n ? decodeColorPickInfo(new Uint8Array(pixelData.buffer, pixelData.byteOffset, 4))\n : null;\n }\n\n protected hasPickInfoChanged(pickInfo: PickInfo): boolean {\n return (\n pickInfo.objectIndex !== this.pickInfo.objectIndex ||\n pickInfo.batchIndex !== this.pickInfo.batchIndex\n );\n }\n\n protected updateTooltip(pickInfo: PickInfo, mousePosition: [number, number]): void {\n const tooltipText = this.props.getTooltip(pickInfo);\n if (!tooltipText) {\n this.hideTooltip();\n return;\n }\n\n const tooltipElement = this.getOrCreateTooltipElement();\n if (!tooltipElement) {\n return;\n }\n\n tooltipElement.textContent = tooltipText;\n tooltipElement.style.display = 'block';\n this.positionTooltip(tooltipElement, mousePosition);\n }\n\n protected hideTooltip(): void {\n if (this.tooltipElement) {\n this.tooltipElement.style.display = 'none';\n }\n }\n\n protected getOrCreateTooltipElement(): HTMLDivElement | null {\n if (this.tooltipElement) {\n return this.tooltipElement;\n }\n if (\n typeof document === 'undefined' ||\n typeof window === 'undefined' ||\n typeof HTMLCanvasElement === 'undefined' ||\n typeof this.device.getDefaultCanvasContext !== 'function'\n ) {\n return null;\n }\n\n const canvas = this.device.getDefaultCanvasContext().canvas;\n if (!(canvas instanceof HTMLCanvasElement) || !canvas.parentElement) {\n return null;\n }\n\n const tooltipElement = document.createElement('div');\n tooltipElement.style.position = 'absolute';\n tooltipElement.style.zIndex = '12';\n tooltipElement.style.display = 'none';\n tooltipElement.style.maxWidth = '220px';\n tooltipElement.style.padding = '8px 10px';\n tooltipElement.style.borderRadius = '6px';\n tooltipElement.style.background = 'rgba(15, 23, 42, 0.92)';\n tooltipElement.style.color = '#f8fafc';\n tooltipElement.style.font = '600 13px/1.35 system-ui, sans-serif';\n tooltipElement.style.pointerEvents = 'none';\n tooltipElement.style.whiteSpace = 'nowrap';\n tooltipElement.style.boxShadow = '0 10px 24px rgba(15, 23, 42, 0.22)';\n\n const tooltipParent = canvas.parentElement;\n if (window.getComputedStyle(tooltipParent).position === 'static') {\n tooltipParent.style.position = 'relative';\n }\n tooltipParent.appendChild(tooltipElement);\n this.tooltipElement = tooltipElement;\n return tooltipElement;\n }\n\n protected positionTooltip(tooltipElement: HTMLDivElement, mousePosition: [number, number]): void {\n if (\n typeof HTMLCanvasElement === 'undefined' ||\n typeof this.device.getDefaultCanvasContext !== 'function'\n ) {\n return;\n }\n\n const canvas = this.device.getDefaultCanvasContext().canvas;\n if (!(canvas instanceof HTMLCanvasElement)) {\n return;\n }\n\n const maxLeft = Math.max(\n TOOLTIP_MARGIN_PIXELS,\n canvas.clientWidth - tooltipElement.offsetWidth - TOOLTIP_MARGIN_PIXELS\n );\n const maxTop = Math.max(\n TOOLTIP_MARGIN_PIXELS,\n canvas.clientHeight - tooltipElement.offsetHeight - TOOLTIP_MARGIN_PIXELS\n );\n const left = Math.min(mousePosition[0] + TOOLTIP_OFFSET_PIXELS, maxLeft);\n const top = Math.min(mousePosition[1] + TOOLTIP_OFFSET_PIXELS, maxTop);\n tooltipElement.style.left = `${Math.max(TOOLTIP_MARGIN_PIXELS, left)}px`;\n tooltipElement.style.top = `${Math.max(TOOLTIP_MARGIN_PIXELS, top)}px`;\n }\n}\n\nexport {COLOR_PICKING_MAX_BATCH_INDEX, COLOR_PICKING_MAX_OBJECT_INDEX};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumberArray4} from '@math.gl/types';\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\n/** Default color for auto highlight, a cyan color */\nconst DEFAULT_HIGHLIGHT_COLOR: NumberArray4 = [0, 1, 1, 1];\n\nexport const INVALID_INDEX = -1;\nexport type PickingPayloadMode = 'instance' | 'attribute' | 'vertex';\n\n/**\n * Props for the picking module, which depending on mode renders picking colors or highlighted item.\n * When active, renders picking colors, assumed to be rendered to off-screen \"picking\" buffer.\n * When inactive, renders normal colors, with the exception of selected object which is rendered with highlight\n * can distinguish between 2^32 different objects in each of 2^32 different batches.\n */\nexport type PickingProps = {\n /** Are we picking? I.e. rendering picking colors? */\n isActive?: boolean;\n /** Whether the payload is sourced from a builtin index or a custom integer attribute */\n indexMode?: PickingPayloadMode;\n /** Identifier of the batch currently being rendered */\n batchIndex?: number;\n\n /** Identifier of the highlighted batch */\n highlightedBatchIndex?: number | null;\n /** Set the highlighted object index, or `null` to explicitly clear **/\n highlightedObjectIndex?: number | null;\n /** Color of visual highlight of \"selected\" item () */\n highlightColor?: NumberArray4;\n};\n\n/**\n * Uniforms for the picking module, which renders picking colors and highlighted item.\n * When active, renders picking colors, assumed to be rendered to off-screen \"picking\" buffer.\n * When inactive, renders normal colors, with the exception of selected object which is rendered with highlight\n */\nexport type PickingUniforms = {\n /**\n * When true, renders picking colors. Set when rendering to off-screen \"picking\" buffer.\n * When false, renders normal colors, with the exception of selected object which is rendered with highlight\n */\n isActive: boolean;\n /** Whether the current payload comes from a builtin index or a custom integer attribute */\n indexMode: 0 | 1 | 2;\n /** Identifier of the batch currently being rendered */\n batchIndex: number;\n\n /** Do we have a highlighted item? */\n isHighlightActive: boolean;\n /** Color of visual highlight of \"selected\" item. Note: RGBA components must in the range 0-1 */\n highlightColor: NumberArray4;\n /** Indicates which batch to visually highlight an item in */\n highlightedBatchIndex: number;\n /** Indicates which object index in the batch to highlight */\n highlightedObjectIndex: number;\n};\n\nexport type PickingBindings = {};\n\n// GLSL_UNIFORMS\n\nconst uniformTypes: Required<ShaderModule<PickingProps, PickingUniforms>>['uniformTypes'] = {\n isActive: 'i32',\n indexMode: 'i32',\n batchIndex: 'i32',\n\n isHighlightActive: 'i32',\n highlightedBatchIndex: 'i32',\n highlightedObjectIndex: 'i32',\n highlightColor: 'vec4<f32>'\n};\n\nexport const GLSL_UNIFORMS = /* glsl */ `\\\nprecision highp float;\nprecision highp int;\n\nlayout(std140) uniform pickingUniforms {\n int isActive;\n int indexMode;\n int batchIndex;\n\n int isHighlightActive;\n int highlightedBatchIndex;\n int highlightedObjectIndex;\n vec4 highlightColor;\n} picking;\n`;\n\nexport const WGSL_UNIFORMS = /* wgsl */ `\\\nstruct pickingUniforms {\n isActive: i32,\n indexMode: i32,\n batchIndex: i32,\n\n isHighlightActive: i32,\n highlightedBatchIndex: i32,\n highlightedObjectIndex: i32,\n highlightColor: vec4<f32>,\n};\n\n@group(0) @binding(auto) var<uniform> picking: pickingUniforms;\n`;\n\nfunction getUniforms(props: PickingProps = {}, prevUniforms?: PickingUniforms): PickingUniforms {\n const uniforms = {...prevUniforms} as PickingUniforms;\n\n // picking\n if (props.isActive !== undefined) {\n uniforms.isActive = Boolean(props.isActive);\n }\n\n switch (props.indexMode) {\n case 'instance':\n uniforms.indexMode = 0;\n break;\n case 'attribute':\n uniforms.indexMode = 1;\n break;\n case 'vertex':\n uniforms.indexMode = 2;\n break;\n case undefined:\n // no change\n break;\n }\n\n if (typeof props.batchIndex === 'number') {\n uniforms.batchIndex = props.batchIndex;\n }\n\n switch (props.highlightedObjectIndex) {\n case undefined:\n // Unless highlighted payload explicitly null or set, do not update state\n break;\n case null:\n // Clear highlight\n uniforms.isHighlightActive = false;\n uniforms.highlightedObjectIndex = INVALID_INDEX;\n break;\n default:\n uniforms.isHighlightActive = true;\n uniforms.highlightedObjectIndex = props.highlightedObjectIndex;\n }\n\n switch (props.highlightedBatchIndex) {\n case undefined:\n break;\n case null:\n uniforms.isHighlightActive = false;\n uniforms.highlightedBatchIndex = INVALID_INDEX;\n break;\n default:\n uniforms.isHighlightActive = true;\n uniforms.highlightedBatchIndex = props.highlightedBatchIndex;\n }\n\n if (props.highlightColor) {\n uniforms.highlightColor = props.highlightColor;\n }\n\n return uniforms;\n}\n\n/**\n * Provides support for color-based picking and highlighting.\n *\n * In particular, supports picking a specific instance in an instanced\n * draw call and highlighting an instance based on its picking color,\n * and correspondingly, supports picking and highlighting groups of\n * primitives with the same picking color in non-instanced draw-calls\n *\n * @note Color based picking has the significant advantage in that it can be added to any\n * existing shader without requiring any additional picking logic.\n */\nexport const pickingUniforms = {\n props: {} as PickingProps,\n uniforms: {} as PickingUniforms,\n\n name: 'picking',\n\n uniformTypes,\n defaultUniforms: {\n isActive: false,\n indexMode: 0,\n batchIndex: 0,\n isHighlightActive: false,\n highlightedBatchIndex: INVALID_INDEX,\n highlightedObjectIndex: INVALID_INDEX,\n highlightColor: DEFAULT_HIGHLIGHT_COLOR\n },\n\n getUniforms\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nimport type {PickingBindings, PickingProps, PickingUniforms} from './picking-uniforms';\nimport {pickingUniforms, GLSL_UNIFORMS, WGSL_UNIFORMS, INVALID_INDEX} from './picking-uniforms';\n\nconst source = /* wgsl */ `\\\n${WGSL_UNIFORMS}\n\nconst COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\nconst COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst COLOR_PICKING_MAX_BATCH_INDEX = 254;\n\nfn picking_setObjectIndex(objectIndex: i32) -> i32 {\n return objectIndex;\n}\n\nfn picking_isObjectHighlighted(objectIndex: i32) -> bool {\n return\n picking.isHighlightActive != 0 &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == objectIndex;\n}\n\nfn picking_filterHighlightColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0 || !picking_isObjectHighlighted(objectIndex)) {\n return color;\n }\n\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n if (blendedAlpha == 0.0) {\n return vec4<f32>(color.rgb, 0.0);\n }\n\n let highLightRatio = highLightAlpha / blendedAlpha;\n let blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4<f32>(blendedRGB, blendedAlpha);\n}\n\nfn picking_canEncodePickInfo(objectIndex: i32) -> bool {\n return\n objectIndex != COLOR_PICKING_INVALID_INDEX &&\n objectIndex >= 0 &&\n objectIndex <= COLOR_PICKING_MAX_OBJECT_INDEX &&\n picking.batchIndex >= 0 &&\n picking.batchIndex <= COLOR_PICKING_MAX_BATCH_INDEX;\n}\n\nfn picking_getPickingColor(objectIndex: i32) -> vec4<f32> {\n if (!picking_canEncodePickInfo(objectIndex)) {\n return vec4<f32>(0.0, 0.0, 0.0, 0.0);\n }\n\n let encodedObjectIndex = objectIndex + 1;\n let red = encodedObjectIndex % 256;\n let green = (encodedObjectIndex / 256) % 256;\n let blue = (encodedObjectIndex / 65536) % 256;\n let alpha = picking.batchIndex + 1;\n\n return vec4<f32>(\n f32(red) / 255.0,\n f32(green) / 255.0,\n f32(blue) / 255.0,\n f32(alpha) / 255.0\n );\n}\n\nfn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0) {\n if (!picking_canEncodePickInfo(objectIndex)) {\n discard;\n }\n return picking_getPickingColor(objectIndex);\n }\n\n return color;\n}\n`;\n\nconst vs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int INDEX_PICKING_MODE_INSTANCE = 0;\nconst int INDEX_PICKING_MODE_CUSTOM = 1;\n\nconst int COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\n\nflat out int picking_objectIndex;\n\nvoid picking_setObjectIndex(int objectIndex) {\n switch (picking.indexMode) {\n case INDEX_PICKING_MODE_INSTANCE:\n picking_objectIndex = gl_InstanceID;\n break;\n case INDEX_PICKING_MODE_CUSTOM:\n picking_objectIndex = objectIndex;\n break;\n }\n}\n`;\n\nconst fs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\nconst int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst int COLOR_PICKING_MAX_BATCH_INDEX = 254;\n\nflat in int picking_objectIndex;\n\nbool picking_isFragmentHighlighted() {\n return\n bool(picking.isHighlightActive) &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == picking_objectIndex\n ;\n}\n\nvec4 picking_filterHighlightColor(vec4 color) {\n if (bool(picking.isActive)) {\n return color;\n }\n\n if (!picking_isFragmentHighlighted()) {\n return color;\n }\n\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\nbool picking_canEncodePickInfo(int objectIndex) {\n return\n objectIndex != COLOR_PICKING_INVALID_INDEX &&\n objectIndex >= 0 &&\n objectIndex <= COLOR_PICKING_MAX_OBJECT_INDEX &&\n picking.batchIndex >= 0 &&\n picking.batchIndex <= COLOR_PICKING_MAX_BATCH_INDEX;\n}\n\nvec4 picking_getPickingColor() {\n if (!picking_canEncodePickInfo(picking_objectIndex)) {\n return vec4(0.0);\n }\n\n int encodedObjectIndex = picking_objectIndex + 1;\n int red = encodedObjectIndex % 256;\n int green = (encodedObjectIndex / 256) % 256;\n int blue = (encodedObjectIndex / 65536) % 256;\n int alpha = picking.batchIndex + 1;\n\n return vec4(float(red), float(green), float(blue), float(alpha)) / 255.0;\n}\n\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (!picking_canEncodePickInfo(picking_objectIndex)) {\n discard;\n }\n return picking_getPickingColor();\n }\n\n return color;\n}\n\nvec4 picking_filterColor(vec4 color) {\n vec4 outColor = color;\n outColor = picking_filterHighlightColor(outColor);\n outColor = picking_filterPickingColor(outColor);\n return outColor;\n}\n`;\n\n/**\n * Provides support for object-index based color picking and highlighting.\n */\nexport const picking = {\n ...pickingUniforms,\n name: 'picking',\n source,\n vs,\n fs\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nimport type {PickingBindings, PickingProps, PickingUniforms} from './picking-uniforms';\nimport {pickingUniforms, GLSL_UNIFORMS, WGSL_UNIFORMS, INVALID_INDEX} from './picking-uniforms';\n\nconst source = /* wgsl */ `\\\n${WGSL_UNIFORMS}\n\nconst COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\nconst COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst COLOR_PICKING_MAX_BATCH_INDEX = 254;\n\nfn picking_getInstanceObjectIndex(instanceIndex: u32) -> i32 {\n return i32(instanceIndex);\n}\n\nfn picking_getVertexObjectIndex(vertexIndex: u32) -> i32 {\n return i32(vertexIndex);\n}\n\nfn picking_getAttributeObjectIndex(objectIndex: i32) -> i32 {\n return objectIndex;\n}\n\nfn picking_setObjectIndex(objectIndex: i32) -> i32 {\n return picking_getAttributeObjectIndex(objectIndex);\n}\n\nfn picking_isObjectHighlighted(objectIndex: i32) -> bool {\n return\n picking.isHighlightActive != 0 &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == objectIndex;\n}\n\nfn picking_filterHighlightColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0 || !picking_isObjectHighlighted(objectIndex)) {\n return color;\n }\n\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n if (blendedAlpha == 0.0) {\n return vec4<f32>(color.rgb, 0.0);\n }\n\n let highLightRatio = highLightAlpha / blendedAlpha;\n let blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4<f32>(blendedRGB, blendedAlpha);\n}\n\nfn picking_canEncodePickInfo(objectIndex: i32) -> bool {\n return\n objectIndex != COLOR_PICKING_INVALID_INDEX &&\n objectIndex >= 0 &&\n objectIndex <= COLOR_PICKING_MAX_OBJECT_INDEX &&\n picking.batchIndex >= 0 &&\n picking.batchIndex <= COLOR_PICKING_MAX_BATCH_INDEX;\n}\n\nfn picking_getPickingColor(objectIndex: i32) -> vec4<f32> {\n if (!picking_canEncodePickInfo(objectIndex)) {\n return vec4<f32>(0.0, 0.0, 0.0, 0.0);\n }\n\n let encodedObjectIndex = objectIndex + 1;\n let red = encodedObjectIndex % 256;\n let green = (encodedObjectIndex / 256) % 256;\n let blue = (encodedObjectIndex / 65536) % 256;\n let alpha = picking.batchIndex + 1;\n\n return vec4<f32>(\n f32(red) / 255.0,\n f32(green) / 255.0,\n f32(blue) / 255.0,\n f32(alpha) / 255.0\n );\n}\n\nfn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0) {\n if (!picking_canEncodePickInfo(objectIndex)) {\n discard;\n }\n return picking_getPickingColor(objectIndex);\n }\n\n return color;\n}\n\nfn picking_filterColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n var outColor = color;\n outColor = picking_filterHighlightColor(outColor, objectIndex);\n outColor = picking_filterPickingColor(outColor, objectIndex);\n return outColor;\n}\n`;\n\nconst vs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int INDEX_PICKING_MODE_INSTANCE = 0;\nconst int INDEX_PICKING_MODE_ATTRIBUTE = 1;\nconst int INDEX_PICKING_MODE_VERTEX = 2;\n\nflat out int picking_objectIndex;\n\nvoid picking_setObjectIndex(int objectIndex) {\n switch (picking.indexMode) {\n case INDEX_PICKING_MODE_INSTANCE:\n picking_objectIndex = gl_InstanceID;\n break;\n case INDEX_PICKING_MODE_ATTRIBUTE:\n picking_objectIndex = objectIndex;\n break;\n case INDEX_PICKING_MODE_VERTEX:\n picking_objectIndex = gl_VertexID;\n break;\n }\n}\n`;\n\nconst fs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int COLOR_PICKING_INVALID_INDEX = ${INVALID_INDEX};\nconst int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;\nconst int COLOR_PICKING_MAX_BATCH_INDEX = 254;\n\nflat in int picking_objectIndex;\n\nbool picking_isFragmentHighlighted() {\n return\n bool(picking.isHighlightActive) &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == picking_objectIndex\n ;\n}\n\nvec4 picking_filterHighlightColor(vec4 color) {\n if (bool(picking.isActive)) {\n return color;\n }\n\n if (!picking_isFragmentHighlighted()) {\n return color;\n }\n\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\nbool picking_canEncodePickInfo(int objectIndex) {\n return\n objectIndex != COLOR_PICKING_INVALID_INDEX &&\n objectIndex >= 0 &&\n objectIndex <= COLOR_PICKING_MAX_OBJECT_INDEX &&\n picking.batchIndex >= 0 &&\n picking.batchIndex <= COLOR_PICKING_MAX_BATCH_INDEX;\n}\n\nvec4 picking_getPickingColor() {\n if (!picking_canEncodePickInfo(picking_objectIndex)) {\n return vec4(0.0);\n }\n\n int encodedObjectIndex = picking_objectIndex + 1;\n int red = encodedObjectIndex % 256;\n int green = (encodedObjectIndex / 256) % 256;\n int blue = (encodedObjectIndex / 65536) % 256;\n int alpha = picking.batchIndex + 1;\n\n return vec4(float(red), float(green), float(blue), float(alpha)) / 255.0;\n}\n\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (!picking_canEncodePickInfo(picking_objectIndex)) {\n discard;\n }\n return picking_getPickingColor();\n }\n\n return color;\n}\n\nvec4 picking_filterColor(vec4 color) {\n vec4 outColor = color;\n outColor = picking_filterHighlightColor(outColor);\n outColor = picking_filterPickingColor(outColor);\n return outColor;\n}\n`;\n\n/**\n * Provides object-index based color picking and highlighting.\n */\nexport const picking = {\n ...pickingUniforms,\n name: 'picking',\n source,\n vs,\n fs\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nimport type {PickingBindings, PickingProps, PickingUniforms} from './picking-uniforms';\nimport {pickingUniforms, GLSL_UNIFORMS, WGSL_UNIFORMS, INVALID_INDEX} from './picking-uniforms';\n\n// SHADERS\n\nconst source = /* wgsl */ `\\\n${WGSL_UNIFORMS}\n\nconst INDEX_PICKING_MODE_INSTANCE = 0;\nconst INDEX_PICKING_MODE_ATTRIBUTE = 1;\nconst INDEX_PICKING_MODE_VERTEX = 2;\nconst INDEX_PICKING_INVALID_INDEX = ${INVALID_INDEX}; // 2^32 - 1\n\n/**\n * WGSL shaders need to carry the returned object index through their own stage outputs.\n */\nfn picking_getInstanceObjectIndex(instanceIndex: u32) -> i32 {\n return i32(instanceIndex);\n}\n\nfn picking_getVertexObjectIndex(vertexIndex: u32) -> i32 {\n return i32(vertexIndex);\n}\n\nfn picking_getAttributeObjectIndex(objectIndex: i32) -> i32 {\n return objectIndex;\n}\n\nfn picking_setObjectIndex(objectIndex: i32) -> i32 {\n return picking_getAttributeObjectIndex(objectIndex);\n}\n\nfn picking_isObjectHighlighted(objectIndex: i32) -> bool {\n return\n picking.isHighlightActive != 0 &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == objectIndex;\n}\n\nfn picking_filterHighlightColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0 || !picking_isObjectHighlighted(objectIndex)) {\n return color;\n }\n\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n if (blendedAlpha == 0.0) {\n return vec4<f32>(color.rgb, 0.0);\n }\n\n let highLightRatio = highLightAlpha / blendedAlpha;\n let blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4<f32>(blendedRGB, blendedAlpha);\n}\n\nfn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {\n if (picking.isActive != 0 && objectIndex == INDEX_PICKING_INVALID_INDEX) {\n discard;\n }\n return color;\n}\n\nfn picking_getPickingColor(objectIndex: i32) -> vec2<i32> {\n return vec2<i32>(objectIndex, picking.batchIndex);\n}\n\n`;\n\nconst vs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int INDEX_PICKING_MODE_INSTANCE = 0;\nconst int INDEX_PICKING_MODE_ATTRIBUTE = 1;\nconst int INDEX_PICKING_MODE_VERTEX = 2;\n\nconst int INDEX_PICKING_INVALID_INDEX = ${INVALID_INDEX}; // 2^32 - 1\n\nflat out int picking_objectIndex;\n\n/**\n * Vertex shaders should call this function to set the object index.\n * If using instance or vertex mode, the argument is ignored and 0 can be supplied.\n */\nvoid picking_setObjectIndex(int objectIndex) {\n switch (picking.indexMode) {\n case INDEX_PICKING_MODE_INSTANCE:\n picking_objectIndex = gl_InstanceID;\n break;\n case INDEX_PICKING_MODE_ATTRIBUTE:\n picking_objectIndex = objectIndex;\n break;\n case INDEX_PICKING_MODE_VERTEX:\n picking_objectIndex = gl_VertexID;\n break;\n }\n}\n`;\n\nconst fs = /* glsl */ `\\\n${GLSL_UNIFORMS}\n\nconst int INDEX_PICKING_INVALID_INDEX = ${INVALID_INDEX}; // 2^32 - 1\n\nflat in int picking_objectIndex;\n\n/**\n * Check if this vertex is highlighted (part of the selected batch and object)\n */ \nbool picking_isFragmentHighlighted() {\n return \n bool(picking.isHighlightActive) &&\n picking.highlightedBatchIndex == picking.batchIndex &&\n picking.highlightedObjectIndex == picking_objectIndex\n ;\n}\n\n/**\n * Returns highlight color if this item is selected.\n */\nvec4 picking_filterHighlightColor(vec4 color) {\n // If we are still picking, we don't highlight\n if (bool(picking.isActive)) {\n return color;\n }\n\n // If we are not highlighted, return color as is\n if (!picking_isFragmentHighlighted()) {\n return color;\n }\n \n // Blend in highlight color based on its alpha value\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\n/*\n * Returns picking color if picking enabled else unmodified argument.\n */\nivec4 picking_getPickingColor() {\n // Assumes that colorAttachment0 is rg32int\n // TODO? - we could render indices into a second color attachment and not mess with fragColor\n return ivec4(picking_objectIndex, picking.batchIndex, 0, 0);\n}\n\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (picking_objectIndex == INDEX_PICKING_INVALID_INDEX) {\n discard;\n }\n }\n return color;\n}\n\n/*\n * Returns picking color if picking is enabled if not\n * highlight color if this item is selected, otherwise unmodified argument.\n */\nvec4 picking_filterColor(vec4 color) {\n vec4 outColor = color;\n outColor = picking_filterHighlightColor(outColor);\n outColor = picking_filterPickingColor(outColor);\n return outColor;\n}\n`;\n\n/**\n * Provides support for color-based picking and highlighting.\n *\n * In particular, supports picking a specific instance in an instanced\n * draw call and highlighting an instance based on its picking color,\n * and correspondingly, supports picking and highlighting groups of\n * primitives with the same picking color in non-instanced draw-calls\n *\n * @note Color based picking has the significant advantage in that it can be added to any\n * existing shader without requiring any additional picking logic.\n */\nexport const picking = {\n ...pickingUniforms,\n name: 'picking',\n source,\n vs,\n fs\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport type {Device} from '@luma.gl/core';\n\nimport type {PickingBindings, PickingProps, PickingUniforms} from './picking-uniforms';\nimport {pickingUniforms} from './picking-uniforms';\nimport {picking as colorPicking} from './color-picking';\nimport {picking as indexColorPicking} from './index-color-picking';\nimport {picking as indexPicking} from './index-picking';\nimport {supportsIndexPicking} from './picking-manager';\n\n/**\n * Unified object-picking shader module.\n * Uses color picking on GLSL/WebGL paths and index picking on WGSL/WebGPU paths.\n */\nexport const picking = {\n ...pickingUniforms,\n name: 'picking',\n source: indexPicking.source,\n vs: colorPicking.vs,\n fs: colorPicking.fs\n} as const satisfies ShaderModule<PickingProps, PickingUniforms, PickingBindings>;\n\n/** Returns the object-index picking shader module supported by this device. */\nexport function getIndexPickingModule(device: Device): typeof indexPicking {\n return (supportsIndexPicking(device) ? indexPicking : indexColorPicking) as typeof indexPicking;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Framebuffer} from '@luma.gl/core';\nimport {picking} from '@luma.gl/shadertools';\nimport {ShaderInputs} from '../../shader-inputs';\nimport {NumberArray3} from '@math.gl/types';\n\n/**\n * Helper class for using the legacy picking module\n */\nexport class LegacyPickingManager {\n device: Device;\n framebuffer: Framebuffer | null = null;\n shaderInputs: ShaderInputs<{picking: typeof picking.props}>;\n\n constructor(device: Device, shaderInputs: ShaderInputs) {\n this.device = device;\n this.shaderInputs = shaderInputs as ShaderInputs<{picking: typeof picking.props}>;\n }\n\n destroy() {\n this.framebuffer?.destroy();\n }\n\n getFramebuffer() {\n if (!this.framebuffer) {\n this.framebuffer = this.device.createFramebuffer({\n colorAttachments: ['rgba8unorm'],\n depthStencilAttachment: 'depth24plus'\n });\n }\n return this.framebuffer;\n }\n\n /** Clear highlighted / picked object */\n clearPickState() {\n this.shaderInputs.setProps({picking: {highlightedObjectColor: null}});\n }\n\n /** Prepare for rendering picking colors */\n beginRenderPass() {\n const framebuffer = this.getFramebuffer();\n framebuffer.resize(this.device.getCanvasContext().getDevicePixelSize());\n\n this.shaderInputs.setProps({picking: {isActive: true}});\n\n const pickingPass = this.device.beginRenderPass({\n framebuffer,\n clearColor: [0, 0, 0, 0],\n clearDepth: 1\n });\n\n return pickingPass;\n }\n\n updatePickState(mousePosition: [number, number]) {\n const framebuffer = this.getFramebuffer();\n\n // use the center pixel location in device pixel range\n const [pickX, pickY] = this.getPickPosition(mousePosition);\n\n // Read back\n const color255 = this.device.readPixelsToArrayWebGL(framebuffer, {\n sourceX: pickX,\n sourceY: pickY,\n sourceWidth: 1,\n sourceHeight: 1\n });\n // console.log(color255);\n\n // Check if we have\n let highlightedObjectColor: NumberArray3 | null = [...color255].map(\n x => x / 255\n ) as NumberArray3;\n const isHighlightActive =\n highlightedObjectColor[0] + highlightedObjectColor[1] + highlightedObjectColor[2] > 0;\n\n if (!isHighlightActive) {\n highlightedObjectColor = null;\n }\n\n this.shaderInputs.setProps({\n picking: {isActive: false, highlightedObjectColor}\n });\n }\n\n /**\n * Get pick position in device pixel range\n * use the center pixel location in device pixel range\n */\n getPickPosition(mousePosition: [number, number]): [number, number] {\n const devicePixels = this.device.getCanvasContext().cssToDevicePixels(mousePosition);\n const pickX = devicePixels.x + Math.floor(devicePixels.width / 2);\n const pickY = devicePixels.y + Math.floor(devicePixels.height / 2);\n return [pickX, pickY];\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {picking as shadertoolsPicking} from '@luma.gl/shadertools';\n\n/** @deprecated Use `picking`/`colorPicking` for object picking. */\nexport const legacyColorPicking = shadertoolsPicking;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BAAAA;EAAA,oBAAAA;EAAA;;;;;;iBAAAA;EAAA;;;;;;;;;ACIA,kBAAkB;AAeZ,IAAgB,0BAAhB,MAAuC;;EAE3C;;EAEA,UAAmB;;EAEnB,QAAgB;;EAEhB,YAAoB;EAEpB,YAAY,QAAsC,CAAA,GAAE;AAClD,SAAK,OAAO,MAAM,QAAQ;AAC1B,WAAO,OAAO,MAAM,KAAK;EAC3B;;EAGA,QAAQ,QAAc;AACpB,QAAI,CAAC,KAAK,SAAS;AACjB;IACF;AAEA,UAAM,sBAAsB,SAAS;AACrC,UAAM,oBAAoB,sBAAsB,KAAK,aAAa,KAAK;AACvE,SAAK,UAAU,gBAAgB;EACjC;;AAOI,IAAO,WAAP,MAAe;;EAEV;;EAEA;EAET,YAAY,OAAc;AACxB,SAAK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d,UAAM,oBACJ,uBAAuB,CAAC,IAAI,uBAAuB,CAAC,IAAI,uBAAuB,CAAC,IAAI;AAEtF,QAAI,CAAC,mBAAmB;AACtB,+BAAyB;IAC3B;AAEA,SAAK,aAAa,SAAS;MACzB,SAAS,EAAC,UAAU,OAAO,uBAAsB;KAClD;EACH;;;;;EAMA,gBAAgB,eAA+B;AAC7C,UAAM,eAAe,KAAK,OAAO,iBAAgB,EAAG,kBAAkB,aAAa;AACnF,UAAM,QAAQ,aAAa,IAAI,KAAK,MAAM,aAAa,QAAQ,CAAC;AAChE,UAAM,QAAQ,aAAa,IAAI,KAAK,MAAM,aAAa,SAAS,CAAC;AACjE,WAAO,CAAC,OAAO,KAAK;EACtB;;;;AC7FF,IAAAC,sBAA4C;AAGrC,IAAM,qBAAqB,oBAAAC;;;A7D2K3B,IAAM,eAAe;",
|
|
6
6
|
"names": ["picking", "import_core", "import_core", "import_core", "import_shadertools", "import_core", "import_core", "import_core", "source", "source", "import_core", "import_core", "module", "import_core", "uniformTypes", "module", "uniformTypes", "import_core", "source", "import_core", "module", "source", "getUniforms", "vs", "fs", "_a", "import_core", "module", "module", "import_core", "import_shadertools", "import_shadertools", "import_core", "import_core", "size", "import_core", "source", "vs", "fs", "import_core", "import_core", "import_core", "import_core", "import_core", "source", "import_core", "import_shadertools", "import_core", "fs", "import_core", "import_shadertools", "import_types", "LOG_DRAW_PRIORITY", "LOG_DRAW_TIMEOUT", "getPlatformInfo", "module", "source", "getUniforms", "import_core", "source", "vs", "fs", "picking", "source", "vs", "fs", "picking", "picking", "import_shadertools", "shadertoolsPicking"]
|
|
7
7
|
}
|